Initializing a compound in c

I was wondering if the union variable would be initialized as a structural 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 intialized c also gets intialized ..
in the code below ... if the integer of the union member also gets initialized with an array of characters, this fragment will give the result 515 ...
(I checked 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 memory allocation, can it initialize int i or not .. (hex value of int i in this code is set to 0x990203).
I think 99 is a result that shows that the higher bits are not intialized.
I'm right?..

+4
source share
3 answers

Reading from a member of a union other than the last written on the outside of the "byte trail" of the member to which you recently wrote results in undefined unspecified behavior. You should not read i until you write to him: whatever you see, there is unbearable garbage.

EDIT 1 Edited in response to Christophe's comment.

+2
source

I think 99 is a result that shows that the higher bits are not intialized .. am I right? ..

That's right, because you just assign two bytes explicitly in the second example, so two bytes of an integer remain uninitialized. In the first example, you assign 4 to i , which is an integer and is divided by byte with c . However, if both members of the union are of the same type, it is assumed that both of them will be initialized correctly. In addition, the space allocated for combining is the space occupied by its largest member, so assuming that some of the bytes i will change when you assign c[x] will not be an error.

The different values ​​that you can see for uninitialized bytes with different initialization methods do not matter in different areas and contexts, are case-specific and are not defined. However, I can not comment on 515, because I do not understand how you get this value.

+1
source

Your assignment via char can lead to undefined behavior if the new value is a trap representation (rare) for type int .

Your union example is not initialization, but only purpose, and thus it only accurately changes the numbers you are referring to, and the rest are left with undefined values. It is always useful for unions to initialize the widest member, something like

 union a ob = { .i = 0 }; 

This way you can ensure that all bytes of your object are initialized to 0 .

+1
source

Source: https://habr.com/ru/post/1402915/


All Articles