Thread: Union problem

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    4

    Union problem

    Can someone please explain me the output of this program. I searched a lot on the net but didn't find any explanation on this type of question on union.

    The output is coming 268 0

    Code:
    #include<stdio.h>
    int main()
    {
    	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);
    return 0;
    }
    Thanx

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    256 * 1 + 12 = 268
    This simply means that your initialization pertains to the char portion of the struct. Placing 1 in the upper byte and 12 in the lower. This also indicates little-endian byte order of your particular processor.

  3. #3
    Registered User
    Join Date
    Feb 2011
    Posts
    4
    Quote Originally Posted by nonoob View Post
    256 * 1 + 12 = 268
    This simply means that your initialization pertains to the char portion of the struct. Placing 1 in the upper byte and 12 in the lower. This also indicates little-endian byte order of your particular processor.
    Thanx. Can you please explain in a little detail that why is the output of u.st.b is 0? and how exactly is the initialization happening in the union?

  4. #4
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    Code:
    Assuming you're on a 32-bit (little endian) machine, the union will be 64 bits long. Initializing with {12, 1} gives:
    
    00110000 10000000 00000000 00000000
    
    Note that the first struct is 4 chars long, which is 32 bits total. Therefore, no matter what you set those chars to, it will never go past the first 32 bits of the 64 bit union, and so the second int will never be touched. Unless of course you explicitly set the u.st.b directly.
    Posted in code tags because it wouldn't let me post otherwise.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem in Union Array program
    By Armaan Bhati in forum C Programming
    Replies: 3
    Last Post: 05-07-2011, 07:29 AM
  2. Accessing bit fields using a union problem.
    By samdomville in forum C Programming
    Replies: 6
    Last Post: 12-10-2008, 04:39 PM
  3. Help With Union-Find Problem
    By Bnchs in forum C++ Programming
    Replies: 0
    Last Post: 12-02-2007, 09:17 AM
  4. Problem with using a union into a struct :)
    By g_p in forum C Programming
    Replies: 11
    Last Post: 05-12-2007, 03:21 PM
  5. Problem with 'union REGS in, out;'
    By JLBSchreck in forum C++ Programming
    Replies: 3
    Last Post: 05-14-2003, 12:57 AM

Tags for this Thread