C Programming - Complicated Declarations - Discussion

Discussion Forum : Complicated Declarations - Point Out Errors (Q.No. 1)
1.
Point out the error in the following program (in Turbo C under DOS).
#include<stdio.h>

union emp
{
    int empno;
    int age;
};

int main()
{
    union emp e = {10, 25};
    printf("%d %d", e.empno, e.age);
    return 0;
}
Error: Lvalue required
Error: Rvalue required
Error: cannot initialize more than one union member.
No error
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
9 comments Page 1 of 1.

VCillusion said:   1 decade ago
union emp e = {10, 25};.

As we can see in above statement both of the members are initialized.

This is not possible as single memory slot is available which is property of union which comes with this one drawback too.

So this is not allowed as maximum of member function only 2 bytes is allocated to emp union so how could it use this 2 byte memory to initialize all member function at once.

I hope it makes it clear.

Raja Ghosh said:   1 decade ago
However we can pass as many values as in the union variable.

But union only gets initialized with one value (leftmost in the parenthesis as per comma operator usage) so here it will take 10.

So the programs runs correctly with warning as: excess elements in union initializer.

But as a programmer we can ignore warnings :).

Vishu said:   9 years ago
@Anjali,
The answer is 10 10 only.
Because, in memory 10 is stored. When we accessing e.empno, it gives 10, still in memory 10 is stored until you initialize another value. So, when you access e.age it gives 10 as value.

Correct me if I made any mistake. Thank you.

Anjali said:   9 years ago
Then what will be the output of this correctified code?

#include<stdio.h>
union emp
{
int empno;
int age;
};

int main()
{
union emp e = {10};
printf("%d %d", e.empno, e.age);
return 0;
}

Shashank said:   1 decade ago
I did this with gcc compiler. No errors but there were two warning.

prog.c: In function 'main':
prog.c:11: warning: excess elements in union initializer
prog.c:11: warning: (near initialization for 'e')

Output: 10 10

Vedasri said:   1 decade ago
When I run the in the gcc compiler I didn't get any warnings or errors. Then answer should be no errors. It is being compiled and executed.

Trinath said:   1 decade ago
I think structures and unions declaration is same but diff is only in memory allocation, so no errors is displayed.

Ryan said:   1 decade ago
When we run on indiabix online compiler it gives output:10 10. Why so?

Ayesha said:   1 decade ago
Please anybody explain me in detail.

Post your comments here:

Your comments will be displayed after verification.