Reputation: 455
i was wondering whether union variable will be initialized like a structure variable or not...
#include<stdio.h>
int main(void)
{
struct a
{
int i;
char c;
};
struct a ob={4};
printf("%d",ob.c);
}
the above code gives 0 as output..
so when i is intialized c also gets intialized..
in the below code...if the union member integer also gets intialized with the character array this snippet would give the output 515...
(i verified it by allocating memory for the union variable using malloc..it works fine.)
#include<stdio.h>
int main(void)
{
union a
{
int i;
char c[2];
};
union a ob;
ob.ch[0]=3;
ob.ch[1]=2;
printf("%d",ob.i);
return 0;
}
but without allocating memory whether it could intialize the int i or not..(the hex value of int i in this code is set to 0x990203).
i think that 99 is the result that shows that the higher bits are not intialized..
am i correct?..
Upvotes: 4
Views: 1781
Reputation: 97948
i think that 99 is the result that shows that the higher bits are not intialized.. am i correct?..
Correct because you only assign to two bytes explicitly in your second example, so two bytes of the integer remain uninitialized. In the first example you assign 4
to i
, which is an integer and shares a byte with c
. However, If both union members are of same type, then assuming that both will be initialized is correct. Also, the space allocated for a union is the space taken by its largest member so assuming some of the bytes of i
will change when you assign to c[x]
would not be wrong.
The different values you may see for uninitialized bytes with different initialization methods, in different scopes and contexts are irrelevant, case specific and not defined. However, I cannot comment on 515 as it is not clear to me how you get that value.
Upvotes: 1
Reputation: 78903
Your assignment through the char
could lead to undefined behavior if the new value happens to be a trap representation (rare) for the type int
.
Your example with the union
is not an initialization but only an assignment and thus it only changes exactly the bytes that you are accessing and the other stay with unspecific values. For unions it is always a good idea to do an initialization of the widest member something like
union a ob = { .i = 0 };
Thereby you can guarantee that all bytes of your object are initialized by 0
.
Upvotes: 1
Reputation: 726529
Reading from a member of the union other than the one most recently written to outside the "byte footprint" of the member to which you have most recently written leads to undefined unspecified behavior. You should not be reading i
until after you have written to it: Whatever you see there is non-portable junk.
EDIT 1 Edited in response to Cristoph's comment.
Upvotes: 2