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 ) ;
}
It is important to note that a static variable must be initialized by a constant literal; we cannot use a function's return value to initialize a static variable. In Example3. c, we try to initialize a static variable by using the return value of fun1().
Yes you are returning an array, which is actually a pointer behind the scenes, to the address of the memory location where the contents of the variable you've initialised is stored.
Functions in C++ can return a reference as it's returns a pointer. When function returns a reference it means it returns a implicit pointer.
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
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 main
function 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 behavior
"hello"[0] = '5';
"why am I not legal?"[0] = '5';
Both 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 this
((char*)"hello")[0] = '5';
((char*)"why am I not legal?")[0] = '5';
Read C++ strings: [] vs *
Only the pointer is static and it points to a constant string. Doing leg[ 0 ] = '5' is not ok as it modifies the constant string.
static make little difference in this case, this is really the same:
char* alsoNotLegal()
{
return "why am I not legal?";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With