Do string constants persist out of scope?
Chris Torek
chris at mimsy.umd.edu
Mon Jan 15 04:11:59 AEST 1990
In article <1380 at mit-amt.MEDIA.MIT.EDU> adamk at mit-amt.MEDIA.MIT.EDU
(Adam Kao) writes:
>If I define a string constant in a procedure and then pass it back
>out, does the pointer I get remain valid? I'm confused because
>strings are really char pointers.
(The specific answer is in `d.' below, for the impatient.) Strings
are not char pointers, although they can be found via char pointers.
String constants---that is, things written as
"text"
---are objects with:
a. Type. This is the first question to ask about any object
or value in C. Nothing else can be decided without this
information.
The type of a string constant is `array N of char', where N is one
more than the number of characters in the string. In ANSI C, the
`char's in the array must not be modified by the programmer;
nonetheless, the type is not `array N of const char'. (The reason
for this has to do with some aspects of type compatibility that
are, in my opinion, bogus.)
b. Value. (This is the next question, once you have the type.)
The value of a string constant is the sequence of characters
enclosed in quotes (backslash escapes having been interpreted
in the process), followed by a character with ordinal value
zero (often called `NUL', or `the null character': do not
confuse this with `NULL').
c. Scope. An object with a name has a scope (one of block, file,
or `external' [meaning global]); this tells you how far away
you can get before the name becomes invisible. The keyword
`static' in a declaration can change the default scope of a name.
A string constant has no name, hence no scope.
d. Storage duration. An object has some location in memory, and
that memory has a lifetime. There are two durations, called
`automatic' and `static'. Note that this `static' differs from
the C keyword `static'. Only objects with block scope may have
automatic duration: everything else has static duration. Objects
with block scope have automatic duration unless they are declared
with the keyword `static'.
A string constant has no scope, hence it has static duration.
Thus, a string constant is an unnamed object of type `array N of char',
with the obvious value, that has no scope and has static duration. It
is therefore safe to obtain a pointer to any of the `char's making up
the array, and follow that pointer at any time later during the program.
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris at cs.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list