return "chars"

V

vl106

char* foo () {
return "abc";
}

I compiled the above code both with MSVC and GCC for PPC. The string
"abc" is generated as a global entity. Thus (1) foo doesn't return a
temporary
and (2) no deallocation is necessary.

What does the standard say about this? Is this a "feature" I can rely on on
every
platform?
 
R

Richard Heathfield

vl106 said:
char* foo () {
return "abc";
}

I compiled the above code both with MSVC and GCC for PPC. The string
"abc" is generated as a global entity. Thus (1) foo doesn't return a
temporary
and (2) no deallocation is necessary.

What does the standard say about this?

"A character string literal has static storage duration"

and

"An object declared with external or internal linkage, or with the
storage-class specifier static has static storage duration. For such an
object, storage is reserved and its stored value is initialized only once,
prior to program startup. The object exists and retains its last-stored
value throughout the execution of the entire program."

Is this a "feature" I can rely on on every platform?

Yes, string literals have static storage duration, and exist for the whole
lifetime of the program.

Just one suggestion, though - I really think you ought to return const char
* rather than char *. You wouldn't want your calling code to try to
/modify/ that string, would you now?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top