13
#include <stdio.h>
union p
{
    int x;
    char y;
}
k = {.y = 97};

int main()
{
    printf("%d\n", k.y);
    return 0;
}

OUTPUT: 97

I came across this Question. As we know we can only initialize the first member of Union. But in this, at the time of initialization, the y variable is initialized through some given method!

Can anyone explain this to me how k={ .Y=97} is breaking the rule stated in Dennis Ritchie's book "Union can only be initialized with a value of the type of its first member" and initializing the second variable instead ?

juan.facorro
  • 9,791
  • 2
  • 33
  • 41

1 Answers1

15

K&R is a great book, but it is old. In C99 You can do this.

Using a designated initializer in the same example, the following initializes the second union member age :

union {
       char birthday[9];
       int age;
       float weight;
      } people = { .age = 14 };
  • You say "K&R ... is old". I tend to think, in the computer world, 35 years (1st edition was 1978) is somewhat beyond "old"... Even the 2nd edition, which IIRC was 1988, is "old"... – twalberg Jul 15 '13 at 19:48