Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are global anonymous unions required to be declared as static?

C++ 0x draft

9.5.6 Anonymous unions declared in a named namespace or in the global namespace shall be declared static.

Why is this?

like image 813
Vatsan Avatar asked Nov 02 '10 03:11

Vatsan


2 Answers

Suppose anonymous unions were not required to be declared static, and the compiler encounters these two translation-units (after preprocessing):

File1:

union {
  int  a;
  char b;
};

// Further contents referring to a and b

File2:

union {
  int  a;
  char b;
};

// Further (different) contents referring to a and b

Are those two unions one an the same object, or are they supposed to be different objects?

I think that, in order to avoid unanswerable questions like this, it has been decided that namespace-scope anonymous unions have to be declared static.

like image 78
Bart van Ingen Schenau Avatar answered Oct 04 '22 22:10

Bart van Ingen Schenau


My guess is that if it were allowed to define the union in a non static way it may violate the ODR (one definition rule)

like image 33
lothar Avatar answered Oct 04 '22 22:10

lothar