×

Two return statements in a function

 0 int func(int a, int b)  { if (a>b) { return a+1; } cout<<" hello"<

 0 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 a = 9 , b = 9 a = 8 , b = 9 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. answered 30 Jan '15, 16:41 1.1k●3●13 accept rate: 36%
 0 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. answered 30 Jan '15, 16:39 46●4 accept rate: 16%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×67
×46
×7

question asked: 30 Jan '15, 16:33

question was seen: 798 times

last updated: 30 Jan '15, 17:09