return "chars"

Discussion in 'C Programming' started by vl106, Jan 14, 2006.

  1. vl106

    vl106 Guest

    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?
    vl106, Jan 14, 2006
    #1
    1. Advertising

  2. 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)
    Richard Heathfield, Jan 14, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Greenhorn
    Replies:
    15
    Views:
    796
    Keith Thompson
    Mar 6, 2005
  2. Kosio

    Floats to chars and chars to floats

    Kosio, Sep 16, 2005, in forum: C Programming
    Replies:
    44
    Views:
    1,246
    Tim Rentsch
    Sep 23, 2005
  3. Hongyu
    Replies:
    9
    Views:
    887
    James Kanze
    Aug 8, 2008
  4. chris cannady

    ctypes return char array with null chars

    chris cannady, Apr 19, 2010, in forum: Python
    Replies:
    1
    Views:
    735
    Mark Tolonen
    Apr 19, 2010
  5. M.Posseth

    receiving ??? chars instead of "special" chars

    M.Posseth, Nov 15, 2004, in forum: ASP .Net Web Services
    Replies:
    3
    Views:
    215
    Dan Rogers
    Nov 16, 2004
Loading...

Share This Page