function - "life-time" of string literal in C -
wouldn't pointer returned following function inaccessible?
char *foo( int rc ) { switch (rc) { case 1: return("one"); case 2: return("two"); default: return("whatever"); } }
so lifetime of local variable in c/c++ practically within function, right? means, after char* foo(int)
terminates, pointer returns no longer means anything?
i'm bit confused lifetime of local var. give me clarification?
yes, lifetime of local variable within scope({
,}
) in created.
local variables have automatic or local storage.
automatic because automatically destroyed once scope within created ends.
however, have here string literal, allocated in implementation defined read memory. string literals different local variables , remain alive throughout program lifetime.they have static duration [ref 1] lifetime.
a word of caution!
however, note attempt modify contents of string literal undefined behavior. user programs not allowed modify contents of string literal.
hence, encouraged use const
while declaring string literal.
const char*p = "string";
instead of,
char*p = "string";
in fact, in c++ deprecated declare string literal without const
though not in c. however, declaring string literal const
gives advantage compilers give warning in case attempt modify string literal in second case.
#include<string.h> int main() { char *str1 = "string literal"; const char *str2 = "string literal"; char source[]="sample string"; strcpy(str1,source); //no warning or error uundefined behavior strcpy(str2,source); //compiler issues warning return 0; }
output:
cc1: warnings being treated errors
prog.c: in function ‘main’:
prog.c:9: error: passing argument 1 of ‘strcpy’ discards qualifiers pointer target type
notice compiler warns second case not first.
edit: answer q being asked couple of users here:
what deal integral literals?
in other words code valid:
int *foo() { return &(2); }
the answer is, no code not valid, ill-formed & give compiler error.
like:
prog.c:3: error: lvalue required unary ‘&’ operand
string literals l-values, i.e: can take address of string literal cannot change it's contents.
however, other literals(int
,float
,char
etc) r-values(c standard uses term the value of expression these) & address cannot taken @ all.
[ref 1]c99 standard 6.4.5/5 "string literals - semantics":
in translation phase 7, byte or code of value 0 appended each multibyte character sequence results string literal or literals. the multibyte character sequence used initialize array of static storage duration , length sufficient contain sequence. character string literals, array elements have type char, , initialized individual bytes of multibyte character sequence; wide string literals, array elements have type wchar_t, , initialized sequence of wide characters...
it unspecified whether these arrays distinct provided elements have appropriate values. if program attempts modify such array, behavior undefined.
Comments
Post a Comment