Two return statements in a function

function
return
statement

#1

int func(int a, int b)
{

if (a>b)
{
return a+1;
}
cout<<" hello"<<endl;
return a;

}

I have a query. In this case, what will the return value be? If i call the function as int k = func(7,8); then what will get assigned to k? what happens to the return statement at the end of the func(…)? Does it get skipped or does initial return get overridden?
Please help me interpret this function and how it will return a value.


#2

hello

will be printed and k will get a value of 7.

your code say that if a>b then k will be assigned a+1;
else
print “hello” and k will be assigned a

in func(7,8) 7<8 so print hello and return 7

Note that once a value is returned from a function all further executions will stop.


#3

If you call the function as int k = func(7,8); then 7 will be assigned to k.

This is because if(a>b) condition evaluates false (as 7>8 is false), hello will be printed and a ( 7 is this case ).

To answer your next doubt "Does it get skipped or does initial return get overridden? " , you need to understand how a function call and return mechanism woks.

Whenever a return statement is executed, will return the value to be returned back to the caller, the next statements will not be executed i.e., the function will be terminated.

If there are multiple return statements (like in your example), there can obviously be multiple execution paths - and they can return different values. In a non-void function every possible execution path has to return something.

Consider three examples

  1. a = 9 , b = 9
  2. a = 8 , b = 9
  3. a = 9 , b = 8

Case 1 : k = func (9,9); will execute if(a>b) and it will be false. So return a+1; will not be executed. The next statement will be executed ( it will print hello ) and return a; will return 9 back to the caller function ( main ), so k=9.

Case 2 : k = func (8,9); will execute if(a>b) and it will be false. So return a+1; will not be executed. The next statement will be executed ( it will print hello ) and return a; will return 8, so k=8.

Case 3: k = func (9,8); will execute if(a>b) and it will be true. So the statement return a+1; inside if block will be executed and the function will exit with value 10 ( a + 1 = 9 + 1 = 10 ). No further statements inside the function will be executed as return statement has already been executed. So the main will have k = 10.

Hope this explanation clears your doubt.