We know , in a union memory is allocated for the element having the maximum size.
So will the following initialization work:
Code:union b { char ch[2]; int i; }; int main() { union b z2={0,2}; return 0; }
We know , in a union memory is allocated for the element having the maximum size.
So will the following initialization work:
Code:union b { char ch[2]; int i; }; int main() { union b z2={0,2}; return 0; }
No, but you can use something like this:
EDIT: It seems to be working, had a typo.Code:union b z2 = { .ch = {0, 2} }
Last edited by Memloop; 06-13-2010 at 07:34 PM.
@Memloop
What does the above code do exactly?Code:union b z2 = { .ch = {0, 2} }
Does it initialize ch to 0 and i to 2??
Yes.
No it doesn't. It initialises z2.ch[0] to 0 (zero) and z2.ch[1] to 2.
I misread it as "initialize ch to 0 and 2".
> So will the following initialization work:
It should do - did you try it?
I believe memloop's answer requires a C99 compiler to work.
Prior to C99, you could only initialise the first named member of the union.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.