Can anybody please mention the differences between a normal and an anonymous union(or struct)?
I have just found one:
functions can't be defined in anonymous union.
Asked
Active
Viewed 1,728 times
5
-
3[unnamed struct/union in C](http://stackoverflow.com/questions/13376494/unnamed-struct-union-in-c), [Anonymous struct/union in C](http://gcc.gnu.org/ml/gcc-patches/1999-06n/msg00376.html) – Grijesh Chauhan Jun 15 '13 at 09:56
2 Answers
7
You don't require dot operator "." to access anonymous union elements.
#include <iostream>
using namespace std;
int main() {
union {
int d;
char *f;
};
d = 4;
cout << d << endl;
f = "inside of union";
cout << f << endl;
}
This will successfully compile in this case but "NO" for normal Union.
Also, Anonymous union can only have public members.
PS :Simply omitting the class-name portion of the syntax does not make a union an anonymous union. For a union to qualify as an anonymous union, the declaration must not declare an object.

S J
- 3,210
- 1
- 22
- 32
-
2Good answer, +1! I had no idea anonymous unions existed :) Just in case any one wants further reading (I did once I read the above answer!) look at section 9.4, bullet points 5 & 6 for some of the other subtleties of C++ spec in INCITS/ISO/IEC 14882-2011[2012]. – Jimbo Jun 15 '13 at 13:40
0
As far as I know, anonymous structs don't exist in standard C++, although they may be supported by some compilers.
Anonymous unions can't have protected or private members. The members are accessed without using the union's name (clearly, as it doesn't have one!). Global anonymous unions (God forbid) must be declared static.

Spalteer
- 454
- 4
- 11