Re: Is this legal ?
- From: "Naresh" <nkprajapati@xxxxxxxxx>
- Date: 14 Sep 2006 22:54:10 -0700
Spiros Bousbouras wrote:
main() wrote:
Hi all,
I wanted to have a union which has two structures in it.
So i did this,
union {
struct{
int a;
int b;
};
struct{
float c;
};
}un;
I did not want to name the two inner structures, because i wanted to
access the members like this,
<union name>.<member name>
instead of
<union name>.<structure name>.<member name>
My question is, Is this valid C?
No. The compiler cannot read your mind and realize
that when you write <union name>.<member name>
you really mean <union name>.<some structure>.<member name>
I also observed that if i have a union like this ,
union {
struct{
int a;
int b;
};
struct{
float a;
float b;
};
}un;
Compiler doesn't give me any error.
If i say, 'un.a' how will it know whether i'm using float a or int
a ?
It won't. Hence your definition is useless even if it
doesn't cause your compiler to complain. For the
programme
int main(void) {
union {
struct{
int a;
int b;
};
struct{
float a;
float b;
};
}un;
}
Sun compiler gives
"b.c", line 6: warning: unnamed union member
"b.c", line 10: warning: unnamed union member
"b.c", line 11: zero-sized struct/union
cc: acomp failed for b.c
gcc -Wall -ansi -pedantic b.c gives
b.c: In function `main':
b.c:6: warning: ANSI C forbids member declarations with no members
b.c:6: warning: unnamed struct/union that defines no instances
b.c:10: warning: ANSI C forbids member declarations with no members
b.c:10: warning: unnamed struct/union that defines no instances
b.c:11: warning: union has no members
b.c:11: warning: unused variable `un'
b.c:12: warning: control reaches end of non-void function
I would suggest that you turn your compiler's warning
levels up. If you still don't get a warning then it's time
to switch to a new compiler.
Thanks for your time,
Yugi.
The main usage of Annonymous Union is to limit scope of some name
space. If you are defining Anno. union, you have to take care scope of
variable yourself.
.
- Follow-Ups:
- Re: Is this legal ?
- From: Jack Klein
- Re: Is this legal ?
- References:
- Is this legal ?
- From: main()
- Re: Is this legal ?
- From: Spiros Bousbouras
- Is this legal ?
- Prev by Date: Re: Is this legal ?
- Next by Date: Re: Need advise on sockets
- Previous by thread: Re: Is this legal ?
- Next by thread: Re: Is this legal ?
- Index(es):
Relevant Pages
|