Wouldn’t the pointer returned by the following function be inaccessible?
char *foo(int rc)
{
switch (rc)
{
case 1:
return("one");
case 2:
return("two");
default:
return("whatever");
}
}
So the lifetime of a local variable in C/C++ is practically only within the function, right? Which means, after char* foo(int) terminates, the pointer it returns no longer means anything, right?
I’m a bit confused about the lifetime of a local variable. What is a good clarification?
Yes, the lifetime of a local variable is within the scope(
{,}) in which it is created.Local variables have automatic or local storage. Automatic because they are automatically destroyed once the scope within which they are created ends.
However, What you have here is a string literal, which is allocated in an implementation-defined read-only memory. String literals are different from local variables and they remain alive throughout the program lifetime. They have static duration [Ref 1] lifetime.
A word of caution!
However, note that any attempt to modify the contents of a string literal is an undefined behavior (UB). User programs are not allowed to modify the contents of a string literal.
Hence, it is always encouraged to use a
constwhile declaring a string literal.instead of,
In fact, in C++ it is deprecated to declare a string literal without the
constthough not in C. However, declaring a string literal with aconstgives you the advantage that compilers would usually give you a warning in case you attempt to modify the string literal in the second case.Sample program:
Output:
Notice the compiler warns for the second case, but not for the first.
To answer the question being asked by a couple of users here:
What is the deal with integral literals?
In other words, is the following code valid?
The answer is, no this code is not valid. It is ill-formed and will give a compiler error.
Something like:
String literals are l-values, i.e: You can take the address of a string literal, but cannot change its contents.
However, any other literals (
int,float,char, etc.) are r-values (the C standard uses the term the value of an expression for these) and their address cannot be taken at all.[Ref 1]C99 standard 6.4.5/5 "String Literals – Semantics":