In the following code, can the value of int be predicted ( how ? ), or it is just the garbage ?
union a
{
int i;
char ch[2];
};
a u;
u.ch[0] = 0;
u.ch[1] = 0;
cout<<u.i;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I would say that depends on the size of
intandchar. Aunioncontains the memory of the largest variable. Ifintis 4 bytes andchar[2]represents 2 bytes, theintconsumes more memory than thechar-array, so you are not initialising the fullint-memory to 0 by setting allchar-variables. It depends on your memory initialization mechanisms but basically the value of theintwill appear to be random as the extra 2 bytes are filled with unspecified values.Besides, filling one variable of a
unionand reading another is exactly what makes unions unsafe in my oppinion.If you are sure that
intis the largest datatype, you can initialize the wholeunionby writingTherefore it may be a good idea to place the largest type at the beginning of the union. Althugh that doesn’t garantuee that all datatypes can be considered zero or empty when all bits are set to 0.