On May 6, 1:41=A0pm, lithium...@[EMAIL PROTECTED]
wrote:
> I'm wondering what is the lifetime of a compile-time string constant,
> I think that is what is called the storage duration of a string
> litteral.
You can use it from the beginning of the program to the end of the
program, just as if it were a global object. Basically, in the context
of your program, it lives forever.
> For example, let's say I've got a void foo(const char*) function, and
> I'm calling it like this:
> foo("simple string");
> For how long can I use the pointer passed to foo?
For the entire program. It's as if you did the following:
char const str[] =3D "simple string"; /* Global object */
int main(void)
{
foo(str);
return 0;
}
> Let's say it stores
> it somewhere, and another function, const char *bar(void) returns the
> pointer passed to foo. Is that pointer still usable in a completely
> different scope.
Yes. Just pretend the string is a global object.
> And I have the same questions with a call like this:
> char *str =3D "simple string";
> foo(str);
Again, "simple string" can be thought of as a global object that will
live for the duration of the entire program. Use it, abuse it, do
whatever you want to it. You can play around with its address of the
entirety of the program.
> The last possibility I can think of is the following:
> char str[] =3D "simple string";
> foo(str);
> That's the only one I think I know: str is an array with automatic
> storage duration, and therefore the pointers that foo gets is valid as
> long as we are in the scope of str. If str is declared like that in
> the beginning of a function named "baz", a call to the previously said
> bar() function would return a valid pointer until the function baz
> exists. Or am I mistaken?
You're correct. Don't let the syntax of:
char str[] =3D "simple string";
fool you. That thing between the inverted commas is NOT a string
literal; it's just a pretty way of writing:
char str[] =3D { 's', 'i', 'm', 'p' ....
And as you know, automatic objects get destroyed when you exit the
block and so any pointers to them become invalid.


|