Are strings local?

Chris Torek chris at mimsy.UUCP
Tue Aug 2 16:11:16 AEST 1988


In article <644 at m10ux.UUCP>, rgr at m10ux.UUCP (Duke Robillard) writes:
>...  According to the first edition of K&R, stuff of the form "this is
>a string" is static (page 181).  This means they are "local to a block"
>(definition of static--page 182).

While static variables are local to the block in which they are defined,
that does not mean that they do not exist outside of that block.  Rather,
it means that they cannot be named outside of that block.

Automatic variables are also local to the block in which they are defined.
The primary difference between static and automatic variables is that
automatic variables are `live' (exist) only during the execution of that
block and any code called from that block, while static variables
exist after that block.

>	char *some_function()
>	{
>	  char *ptr;
>	  ptr= "string";
>	  return(ptr);
>	}

>It seems to me that "string" would only be defined inside some_function.

If strings did not have static storage duration, you would be
correct; and indeed, the alternative version

	char *some_function() {
		char buf[7];
		(void) strcpy(buf, "string");
		return (buf);
	}

is in fact invalid.

>What about ...
>	  ptr= "string";
>	  another_function(ptr);
>
>Again, since another_function is not in the same block and "string" is
>"local to a block" this would seem illegal.

Both `ptr' and `"string"' are still local to the function some_function(),
but here another_function() is called from within some_function(), hence
even without static storage duration, this would be legal.  Note that
the function another_function does not have access to the variable `ptr'
(no matter what [legal things] it does with its argument, `ptr' remains
unchanged).  It has indirect access to "string" only because it has its
own local variable (its argument) which has been made the same value
as `ptr'.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list