Reputation: 65
char str[] = "hello";
This definition dosn't work but
static char str[] = "hello"
This works, why?
Full code:
char *retstr(void)
{
char str[] = "hello"; //This definition dosnt work
return str;
}
int main()
{
printf("\n%s\n",retstr());
return 0;
}
Upvotes: 1
Views: 100
Reputation: 321
Static variables are created once and does not get destroyed when a function returns but local variables gets destroyed once our function ends.
local variable are created every time a function is called and gets destroyed when it returns.
In case of local variable : you are returning a pointer to a string which exists no-more.
In case of global variable : the string is still there and hence it will always work.
Upvotes: 0
Reputation: 134326
In case of
char str[] = "hello"; //This definition dosnt work
you're trying to return the address of a local variable str
. Using the returned value is undefined behaviour here, because once the retstr()
function finishes execution, there is no existence of the str
variable.
OTOH,
static char str[] = "hello";
works, because, the static
variable as static storage duration. Its lifetime is the entire execution of the program. So even after the retstr()
function finishes execution, str
remains valid, and hence, the return value is valid to be used.
Related: C11
, chapter §6.2.4, Storage durations of objects, Paragraph 3
... with the storage-class specifier
static
, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
Upvotes: 3
Reputation: 1844
You cannot return local variables from a function. Local variables live on the stack, and once the function completes, that stack space is released and can be used by the next function call.
char str[] = "hello"; //this won't work as it is a local variable
Once you come out of the scope there doesn't exist any variable named str
for other function calls.
But static
variable lifetime extends across the entire run of the program.
static char str[] = "hello"; //this will work
Hence on using static
it is not giving any error.
Upvotes: 1
Reputation: 1181
char str[] = "hello"; //This definition dosnt work
return str;
Here you are returning the local address. that's why it is not working
static char str[] = "hello"
while in this one, you are changing the scope of the 'str' variable to the whole program. that's why it works.
Upvotes: 1