Static initializers

Evan J. Bigall evan at u1100s.UUCP
Sun Aug 21 05:13:43 AEST 1988


> char *t = "Hello World" ;
> struct bar {
>   char *z ;
>   int y ;
> } x = { t , 10 } ;   /* t is not allowed here*/
>
> main () {
>   printf ("x.z = %s\n",x.z) ;
> }
>
> ok you C-nuts. Question for you. Why do my compilers complain about the 
> initialization of x.z with t? ("initializer for static variable is not 
> constant" -- gcc) It seems pretty constant to me.

No, its not constant.  You are intializing it with t and t is a char* variable.
t also happens to be initialized but, t is not equivalent to "Hello World"

It makes more sense if you think about it from a more general point of view
where the value of t could change between the initialization of it and that 
of x.  Something like:

	main()
	  { char *t = "Hello World";
	
	    /* lots of code, potentially mucking the value of t */ 

	    { /* begin a sub block */

	       struct bar
                  { char *z;
                    int y;  } x = { t , 10 } ; /* who knows what t is here? */

	     }
	   }

Your code will work if you change the initialization to:

	 struct bar {
	   char *z ;
	   int y ;
	 } x = { "Hello World", 10 } ;   /* t is not allowed here*/        


Does this help?
Evan



More information about the Comp.lang.c mailing list