Search code examples
cunions

Union and Struct Initialization


I stumbled across a code based on unions in C. Here is the code:

    union    {  
        struct  {  
            char ax[2];  
            char ab[2];  
        } s;  
        struct  {  
            int a;  
            int b;  
        } st;  
    } u ={12, 1}; 

    printf("%d %d", u.st.a, u.st.b);  

I just couldn't understand how come the output was 268 0. How were the values initialized? How is the union functioning here? Shouldn't the output be 12 1. It would be great if anyone could explain what exactly is happening here in detail.

I am using a 32 bit processor and on Windows 7.


Solution

  • The code doesn't do what you think. Brace-initializes initialize the first union member, i.e. u.s. However, now the initializer is incomplete and missing braces, since u.s contains two arrays. It should be somethink like: u = { { {'a', 'b'}, { 'c', 'd' } } };

    You should always compile with all warnings, a decent compiler should have told you that something was amiss. For instance, GCC says, missing braces around initialiser (near initialisation for ‘u.s’) and missing initialiser (near initialisation for ‘u.s.ab’). Very helpful.

    In C99 you can take advantage of named member initialization to initialize the second union member: u = { .st = {12, 1} }; (This is not possible in C++, by the way.) The corresponding syntax for the first case is `u = { .s = { {'a', 'b'}, { 'c', 'd' } } };, which is arguably more explicit and readable!