Concept Flow - Return values
Function called
Execute function body
Return value computed
Return value sent back
Use returned value in caller
When a function finishes, it sends back a value to where it was called, which can then be used.
int add(int a, int b) { return a + b; } int main() { int result = add(3, 4); return 0; }
| Step | Action | Variables | Return Value | Notes |
|---|---|---|---|---|
| 1 | Call add(3, 4) | a=3, b=4 | N/A | Function starts with parameters 3 and 4 |
| 2 | Calculate a + b | a=3, b=4 | 7 | Sum is 7 |
| 3 | Return 7 to caller | a=3, b=4 | 7 | Function ends, returns 7 |
| 4 | Assign return value to result | result=7 | N/A | Main stores 7 in result |
| 5 | End of main | result=7 | N/A | Program ends |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| a | N/A | 3 | 3 | 3 | N/A | N/A |
| b | N/A | 4 | 4 | 4 | N/A | N/A |
| result | N/A | N/A | N/A | N/A | 7 | 7 |
Return values in C++: - Use 'return' to send a value back from a function. - Function ends immediately after 'return'. - Caller receives the returned value to use. - Variables inside function exist only during call. - Returned value can be stored or used directly.
return statement do in a C++ function?returnreturn statement is used to send a value from a function back to the caller.return specifically sends a value back.return value; with a semicolon.return 5; which is correct. return(5) misses semicolon. Options C and D use invalid syntax.int add() {
return 2 + 3;
}
int main() {
int result = add();
std::cout << result;
return 0;
}int multiply(int a, int b) {
a * b;
}a * b; but does not return it.return before a * b;.return before a * b; -> Option APass the test and this pattern moves unknown