function returns local variable, though variable is out of scope no compiler issues and code executes [closed]

When you do

return (result);

result is returned by value. So, the caller gets a copy of the value in result, and uses this copy subsequently. result itself goes out of scope, and is not accessed again.

If your variable was instead a pointer, it would be incorrect. You can read more about it from this question.

In addition, you seem to have forgotten to use add() at all. I suppose you meant to use

res = add(3,4);

in main() instead of

res = (3 + 4);

Leave a Comment