Doubt on working of "return" in functions

in a int function is it cumpolsory to write return statement befor the } . I wrote a code in which return was passed in if statements and it showed error, although the if statemnt was true , so is it mandatory to return at the end every time (unless it is not void() )?

hi @aggarwal.naman21
Kindly share ur code… will check it…
also it might be the case that the if condition u are checking is not getting satisfied, hence if there is no return statement after that, it will give error…

1 Like

#include
#include
using namespace std;

int FINDTHENO( int a[] ,int n, int m){

int i;     
for( i = 0 ; i<n ; i++)
 {
     if(a[i]==m) 
     {
     return i;
	 
     }
 }
 
if(i==n)
{
return -1;
}
  return 0;

}

int main() {

 int n ;
 int a[n];
 cin>>n;

int i = 0 , m;
 

for( i=0; i<n; i++)
 {
     cin>>a[i];
 }
 cin>>m;
cout<<FINDTHENO(a,n,m);

}

in this code without return 0 it was showing error…

hi @aggarwal.naman21

if(i==n)
{
return -1;
}

u don’t have to write this as well… when u come out of for loop simply return -1, as element would not have been found in that case…

1 Like

ahh ok… thank you very much!

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.