Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ lifetime of a dangling string

In C, you can write

const char *result = "AB";

Is this style supported in C++ by standard? Is the life-time of this constant string guaranteed along with the same scope of the pointer?

like image 814
alex Avatar asked Oct 26 '25 08:10

alex


1 Answers

Literals string constants have a lifetime of the whole program, and the arrays the strings are stored in never go out of scope.

Note that there's a semantic difference between literal strings in C and C++: In C++ literal strings are stored in arrays of constant characters (therefore the const in const char* is needed). In C they aren't constant arrays (so char * is alright in C). However, it's not allowed to modify a literal string in C, which makes them read only (but not constant).

like image 68
Some programmer dude Avatar answered Oct 28 '25 22:10

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!