-6

My function is supposed to return a local variable. It manages to do this without any compiler issues even though variable is out of scope.

int add(int a, int b);
{
    int result=0;
    result = a + b;
    return (result); // result scope should be limited to this method
}

int main()
{
    int res=0;
    res = (3 + 4);
    printf("Result : %d \n", res);
    return 0;
}

Can anyone please explain this behavior.

  • 3
    You are not even calling the `add` function. Care to explain a bit more? And there's a `;` at the end of `add` function definition. – Shubham Apr 23 '17 at 05:07
  • 1
    What behavior are you questioning? – Thomas Matthews Apr 23 '17 at 05:08
  • 1
    Your question makes no sense. You never call the function `add()`, so it can't return anything. There's no issue with a function returning a value from a local variable, anyway. Your `int res = 0;` is useless, if in the next line you assign it `(3 + 4)`, so you could write it as `int res = (3 + 4);` in the first place. You have the same issue in `add()`, which never gets executed anyway because you never call it; you could delete the enture function and your code would still compile and execute. – Ken White Apr 23 '17 at 05:08
  • 1
    Returning a value isn't a problem; returning a pointer to a local variable is a problem. – Jonathan Leffler Apr 23 '17 at 05:08
  • The `return` statement is returning the *value* of the `result` variable, not the actual variable. – Thomas Matthews Apr 23 '17 at 05:09

1 Answers1

1

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);
Community
  • 1
  • 1
GoodDeeds
  • 7,956
  • 5
  • 34
  • 61