Why didn't ANSI make initialisation consistent ????

j chapman flack chap at art-sy.detroit.mi.us
Sat Apr 27 02:55:18 AEST 1991


In article <1991Apr24.141206.18103 at grep.co.uk> vic at grep.co.uk (Victor Gavin) writes:
>   ...
>I traced it back to my use of
>	char *fred = "bert"
>being the same as
>	char fred[] = {'b', 'e', 'r', 't', '\0'}

Ah, but they're not the same.  You can tell by the result of
  sizeof fred
in both cases.  What the first is really (more or less) equivalent to is:

   char bill[] = {'b','e','r','t','\0'};
   char *fred = bill; /* == &(bill[0]) */

It works because "bert" is one of the few types of constant defined into the
C language (i.e., decimal, octal, hex, character, string, that's it).  As a
constant, "bert" is a character array in its own right; it can be used to
initialize a character array, as in

char fred[] = "bert"; /* which *is* the same as char fred[]={'b','e',...} */

or its address can be taken and used to initialize a char pointer, which
happens implicitly in

char *fred = "bert";
>
>Which made me believe that I could use the following code:
>
>	struct bert { int a, b; }
>	struct fred { struct bert *abc; } blip = { {1,1} };
>

The difference is that the C definition doesn't build in a "structure
constant".  {1,1} is not a structure in its own right the way "garbonzo"
is a character array in its own right.  How could it be?--{1,1} doesn't
contain enough information to create a finished struct declaration.  So you
can't just take the address of {1,1} as you could "garbonzo".  You would need
the form:

struct bert { int a, b; } bill = {1,1};
struct fred { struct bert *abc } blip = { &bill };

I hope this helps.  I don't think the problem is an inconsistency in C, it's
just a consequence of C's lack of a "structure constant."  If you wanted to
add such a thing to the langauge, you'd have to define a syntax that included
everything needed to declare an appropriate structure, such as element names,
in the constant.  I think that would add unnecessary complexity to the
langauge.
-- 
Chap Flack                         Their tanks will rust.  Our songs will last.
chap at art-sy.detroit.mi.us                                   -Mikos Theodorakis

Nothing I say represents Appropriate Roles for Technology unless I say it does.



More information about the Comp.lang.c mailing list