Thread: Problem when trying to return union type variable from function

  1. #1
    Registered User
    Join Date
    Jun 2009

    Question Problem when trying to return union type variable from function

    Hi all,

    I have a problem when trying to return a union type variable from function. The union is defined in a header file called "Dummy.h" like that:

    typedef union
            uint32_t A;
            uint32_t B;
    } dummy_union;
    In "Dummy.c", I declared a function called dummy_union() which just saves 0x55 and 0xFF to a "dummy_union" variable "X" and returns it.

    #include "Dummy.h"
    inline  dummy_union Dummy_Task(void)
    dummy_union X;
    X.A = 0x55;
    X.B = 0xFF;
    return X;
    Furthermore, Dummy_caller() calls Dummy_Task() and stores its return to a new "dummy_union" variable "var1". Finally, the 2 members of "var1" are printed.

    void Dummy_caller(void)
    static dummy_union var1;
    printf("member 1 of var1 is %u \n", var1.A);
    printf("member 2 of var1 is %u \n", var1.B);
    However, both printfs give 0xFF. Does anyone have any idea why?


  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    The point of a union is that the different parts share storage, so you can only use one at a time.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Your assignment of .B overwrites your assignment of .A. If you want a struct, use a struct.

    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    Jun 2009
    Thanks for the help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Conversion of pointers to functions
    By hzmonte in forum C Programming
    Replies: 0
    Last Post: 01-20-2009, 01:56 AM
  3. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  4. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM