这个问题是为了更好地理解C++中的静态变量。
我曾经认为,如果在C ++中声明一个变量为静态变量,那么我可以返回对局部变量的引用,因为该变量应该在函数返回后继续存在。为什么这样做不起作用呢?
#include <stdio.h>
char* illegal()
{
char * word = "hello" ;
return word ;
}
char* alsoNotLegal()
{
static char * word = "why am I not legal?" ;
return word ;
}
int main()
{
// I know this is illegal
//char * ill = illegal();
//ill[ 0 ] = '5' ;
//puts( ill ) ;
// but why is this? I thought the static variable should "live on" forever -
char * leg = alsoNotLegal() ;
leg[ 0 ] = '5' ;
puts( leg ) ;
}