0

the below code provided an O/P : 101:name_provided:name_provided

AFAIK a union can hold only one member at a time, but it looks like both values are visible , is that correct or anything wrong with the code.

#include <stdio.h>

struct test1{
    char name[15];
};

struct test2{
    char name[15];  
};

struct data{
    int num;
    union{
        struct test1 test1_struct;
        struct test2 test2_struct;
    };
};

int main()
{
    struct data data_struct={101,"name_provided"};
    printf("\n%d:%s:%s",data_struct.num,data_struct.test1_struct.name,data_struct.test2_struct.name);
    return 0;
}
No_Name__
  • 25
  • 9
  • C doesn't prevent you from accessing a different union member than the one you assigned to, it's just unspecified behavior. Although when both structures are the same, I think it's always OK. – Barmar May 25 '17 at 05:19
  • What do you expectt to happen instead? – n. m. could be an AI May 25 '17 at 05:36
  • @n.m. , only one structure (test1_struct or test2_struct) inside anonymous union can hold the value and the other will print garbage – No_Name__ May 25 '17 at 12:39
  • Sometimes garbage looks legitimate simply becase it randomly lands in a region of memory that happens to store legit values. In your case however the output is well defined and not garbage, because the two union members are 'similar' structs and the language standard specially defines this case. So it is guaranteed to print what it prints (as opposed to "happens to print"). – n. m. could be an AI May 25 '17 at 12:50
  • Also with a small update in code, `struct test1{ char name[10]; }; struct test2{ char name[15]; };` the O/P changed as : `101:name_provi:name_provi` is it like with the below code, `struct data data_struct={101,"name_provided"};` the test1_struct's name will get the value , and the test2_struct's name will print the garbage, than allocating memory with respect to the member with bigger storage . – No_Name__ May 25 '17 at 13:01

1 Answers1

0

A union specifies that both members will be located at the same place in memory. So if you assign to test1_struct and then read from test2_struct, it will interpret the contents of test1_struct as if it were in the format of test2_struct.

In this case, both structures have the same format, so it doesn't make a difference which one you read and write. It generally makes no sense to use a union where both members are equivalent. The usual purpose of a union is to have different types of members, but not need to have separate memory for each of them, because you only need to use one type at a time. See How can a mixed data type (int, float, char, etc) be stored in an array? for a typical use case.

And see Unions and type-punning for the consequences of accessing a different member than the one you assigned to.

Barmar
  • 741,623
  • 53
  • 500
  • 612