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;
}
Error: invalid union declaration
Error: in Initializing z2
No error
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
21 comments Page 2 of 3.

Uma said:   1 decade ago
In unions we can initialize only one member at the declaring of object/variable for the union.

SATYAPRAKASH said:   1 decade ago
YES PRETHI your correct when you assign char var to int value it gives ASCII VALUE.

Mustafa said:   1 decade ago
In gcc compiler its giving only warning, but program is running fine.

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.

Navi said:   1 decade ago
If we want all the variables of an union to be initialized then what should we do?

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

Ashita said:   1 decade ago
How the initialization value of z1 is correct?

Gopi said:   1 decade ago
but when i execute it shows no 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..

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.


Post your comments here:

Your comments will be displayed after verification.