scope of local variables of a function in C

2019-02-18 00:49发布

I have heard about the following scenario right when I started programming in C.

"Trying to access from outside, a functions local variable will result in error (or garbage value). Since the stack gets cleared off when we return from the function"

But my below code sample prints a value of 50. I am compiling the code with latest GCC compiler.

#include <stdio.h>

int * left();

int main()
{
      int *p=left();
      printf("%d\n",*p);
      return 0;
}

int * left()
{
        int i=50;
        return &i;
}

Enlight me on this issue.

Can I know the behaviour in C++ ?? Is it similar to c ..

标签: c++ c scope
8条回答
我想做一个坏孩纸
2楼-- · 2019-02-18 01:28

The behavior according to the C standard is undefined not garbage values. So it's possible, and occasionally likely, that the value will remain unchanged. This is not guaranteed by any means.

This is working by luck / chance / accident and nothing else. Don't rely on this behavior because it will come back to bite you.

查看更多
We Are One
3楼-- · 2019-02-18 01:28

As far as the C standard is concerned, the value is undefined.

Practically, as long as nothing is pushed to the stack before the returned value is referenced, it works, but the next time a function is called the return address and new stack frame are pushed to the stack and may overwrite the referenced value.

This would not be considered acceptable coding (because of the undefined nature).

查看更多
登录 后发表回答