C Programming - Structures, Unions, Enums - Discussion
Discussion Forum : Structures, Unions, Enums - Point Out Errors (Q.No. 8)
8.
Point out the error in the program?
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a z1 = {512};
union a z2 = {0, 2};
return 0;
}
Discussion:
21 comments Page 1 of 3.
Preethi said:
1 decade ago
I guess the variable ch is declared to be as character but int values are assigned to it. Am I correct?.
Nikhil said:
1 decade ago
In union at a time, only one variable can be initialised.. so union a z2={0,2} is an error.
Ashwani said:
1 decade ago
@Preethi:: U R correct but ur answer comes in 2nd the priority list after Nikhil's answer...So i think Nikhil's answer is more appropriate to this question..
Gopi said:
1 decade ago
but when i execute it shows no error
Ashita said:
1 decade ago
How the initialization value of z1 is correct?
Wikiok said:
1 decade ago
Only the 1st variable can be initialized in standard C. But there are some compilers that allows other members initialization:
union a z2 = { .ch[0]=1; .ch[1]=2; };
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fstrin.htm
union a z2 = { .ch[0]=1; .ch[1]=2; };
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fstrin.htm
Navi said:
1 decade ago
If we want all the variables of an union to be initialized then what should we do?
Pradeep said:
1 decade ago
Yes, in union we can create only one object or variable at a time whereas in structure only we can create any number of variables or object. So option (B) is correct. In this program z2 is second variable or object created so it is not possible in union.
Mustafa said:
1 decade ago
In gcc compiler its giving only warning, but program is running fine.
SATYAPRAKASH said:
1 decade ago
YES PRETHI your correct when you assign char var to int value it gives ASCII VALUE.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers