Search code examples
cunions

How to Explain this C Union Output


#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 ?


Solution

  • 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 };