Problem when trying to return union type variable from function

This is a discussion on Problem when trying to return union type variable from function within the C Programming forums, part of the General Programming Boards category; Hi all, I have a problem when trying to return a union type variable from function. The union is defined ...

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    26

    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:

    Code:
    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.

    Code:
    #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.

    Code:
    void Dummy_caller(void)
    {
    static dummy_union var1;
    
    var1=Dummy_Task();
    
    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?

    Thanks!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    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
    Posts
    14,826
    Your assignment of .B overwrites your assignment of .A. If you want a struct, use a struct.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    Jun 2009
    Posts
    26
    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, 08: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 Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 02:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21