Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   return "chars" (http://www.velocityreviews.com/forums/t440891-return-chars.html)

vl106 01-14-2006 09:59 PM

return "chars"
 
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?



Richard Heathfield 01-14-2006 10:05 PM

Re: return "chars"
 
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?


--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


All times are GMT. The time now is 08:06 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.