I am confused as to how we are able to return strings from function.
char* someFunction()
{
return "Hello, World"
}
Shouldn’t the above return statement throw “function returns address of local variable” and how is it different from the function:
char* newFunction()
{
char temp[] = "Hello, World";
return temp;
}
which in fact does give the warning mentioned above.
String literals have static storage duration. You can return a pointer to a string and then access the string, it is perfectly valid and defined behavior.
In the below case, you are returning a pointer to a string with automatic storage duration. An object with automatic storage duration is destroyed after exiting the block where it is defined. So accessing it after the function returns is undefined behavior.