C Programming - Declarations and Initializations - Discussion
Discussion Forum : Declarations and Initializations - Find Output of Program (Q.No. 10)
10.
What is the output of the program?
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0] = 3;
u.ch[1] = 2;
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
return 0;
}
Answer: Option
Explanation:
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i); It prints the value of u.ch[0] = 3, u.ch[1] = 2 and it prints the value of u.i means the value of entire union size.

So the output is 3, 2, 515.
Discussion:
78 comments Page 3 of 8.
Bhushan said:
1 decade ago
How we can calculate the value of u(I) at memory block 512?
Komal said:
1 decade ago
ch is char type of variable then how can we assign it number?
Sjohnson said:
8 years ago
@All.
If sizeof(int) > 4 then the upper bits of a.i is not initialized and the value of u.i can be greater than 0x0203. For example, the 64-bit compiler on my system produces the value 0x7c0203.
However, if I set u.i = 0 before setting u.ch[0], u.ch[1] then it works.
If sizeof(int) > 4 then the upper bits of a.i is not initialized and the value of u.i can be greater than 0x0203. For example, the 64-bit compiler on my system produces the value 0x7c0203.
However, if I set u.i = 0 before setting u.ch[0], u.ch[1] then it works.
Khairul Islam said:
2 months ago
@All.
Here i = ch[1]*256 + ch[0].
Here i = ch[1]*256 + ch[0].
Jayakumar v said:
4 years ago
Good explanation. Thanks, everyone.
Mesi said:
6 years ago
What will be the result if we add one more value u.ch[2]=4?
Mahesh said:
6 years ago
How that I and other two char arrays are related ?
We are asked to find I and how we are relating it with other variables.
We are asked to find I and how we are relating it with other variables.
Harika said:
6 years ago
Can anyone explain the memory allocation?
Please.
Please.
Saila said:
7 years ago
Thank you @Mostafa Hamoda.
Ajay gupta said:
7 years ago
@All.
As explained that how it became 515 and I understood it. But why we need to calculate the size of the union while we are accessing the value of the variable I in the union u. why the size and how u, I is related to the size.
As explained that how it became 515 and I understood it. But why we need to calculate the size of the union while we are accessing the value of the variable I in the union u. why the size and how u, I is related to the size.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers