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 ) ;
}
The two functions are not itself illegal. First, you in both case return a copy of a pointer, which points to an object having static storage duration: The string literal will live, during the whole program duration.
But your
mainfunction is all about undefined behavior. You are not allowed to write into a string literal’s memory 🙂 What your main function does can be cut down to equivalent behaviorBoth are undefined behavior and on some platforms crash (good!).
Edit: Note that string literals have a const type in C++ (not so in C):
char const[N]. Your assignment to a pointer to a non-const character triggers a deprecated conversion (which a good implementation will warn about, anyway). Because the above writings to that const array won’t trigger that conversion, the code will mis-compile. Really, your code is doing thisRead
C++ strings: [] vs *