Search code examples
cconstantsunions

How union works when we print other variables which are not initialized?


#include<stdio.h>
#include<stdlib.h>
union employee
{ 
    char name[15]; 
    int age; 
    float salary; 
};
const union employee e1; 
int main()
{ 
    strcpy(e1.name, "z");
    printf("%s %d %f\n", e1.name, e1.age, e1.salary);
    strcpy(e1.name, "x");
    printf("%s %d %f", e1.name, e1.age, e1.salary);
    return 0; 
}

Output:

z 122 0.000000
x 120 0.000000

union is declared const but why the value is changing? and how the union works when we print other values?


Solution

  • Writing to const data is undefined behavior (UB).

    const union employee e1; 
    strcpy(e1.name, "z");
    

    You are "getting this warning, so strcpy" may or may not correctly perform the copy to a const. Code has broken the contract about writing to const data. Now the compiler not longer needs to behave in a proscribed manner. The code may abruptly fail at this point or it may do anything - including work as desired. That is undefined behavior (UB).