This question is just for my better understanding of static variables in C++.
I thought I could return a reference to a local variable in C++ if it was declared static since the variable should live-on after the function returns. Why doesn't this work?
#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 ) ;
}