Reputation: 1093
Point from ISO C++ Standard: section 9.5, para 4, line 1:
"A union for which objects or pointers are declared is not
an anonymous union."
Example :
struct X {
union {
int i;
double d;
} ;
int f () { return i;}
};
int main() { return 0; }
IAm expecting an error from this example according to the above point
but GCC,SUN compiler CC,EDG,etc are not showing error
iam expecting this error// error : cannot directly access "i"
please ..conform above example program is correct are wrong
Upvotes: 3
Views: 101
Reputation: 473352
To add to what Alf is saying, the purpose of the anonymous union language in the C++ spec is to allow scoping of the unions members. If you have a named union inside a struct:
struct X {
union {
int i;
double d;
} varname;
};
i
is not a member of the struct X. i
is a member of varname
, which itself is a member of struct X
.
However, if the union doesn't have a member variable declared, then i
would have to be accessed directly as a member of X
. This can only work if the union has no name (no variables are declared with the union definition). Such unions are called "anonymous unions".
Upvotes: 3
Reputation: 145259
This would make the union not anonymous:
struct X {
union {
int i;
double d;
} *p;
int f () { return i;} // !Nyet.
};
Cheers & hth.,
Upvotes: 4