C++11 allows an anonymous union to be defined in a function, and its members can be accessed as variables of the function. If I examine the pointers to the different members, they are the same, but the ==
operator says they're unequal.
Such strange behavior is typically the result of undefined behavior, but I don't see anything undefined in my code (I made sure to that both members are of the same type).
The behavior is different if I use a named variable of an unnamed union type. In this case, the pointers compare equal.
This program demonstrates both cases:
#include <iostream>
using namespace std;
#ifdef NAMED
// Create a named object of a union type
#define NAME n
#define ADDR(mem) &(NAME.mem)
#else
// Create an anonymous union in main()
#define NAME
#define ADDR(mem) &mem
#endif
int main()
{
union {
int a;
int b;
} NAME;
cout << "&a = " << ADDR(a) << endl;
cout << "&b = " << ADDR(b) << endl;
cout << "(&a==&b) = " << (ADDR(a) == ADDR(b)) << endl;
return 0;
}
When compiled with -DNAMED
it prints to identical pointers, and 1 (equal pointers). Without -DNAMED
, it again prints identical pointers, but then 0 (unequal pointers).
Tested with g++ 5.4.0, Ubuntu 16.04, x86_64.
ADDR(a) == ADDR(b)
on trunk. – Bewrayvoid*
, your program is well-defined. – Bewray