struct { size_t cap; char ignore[7]; bool isHeap1; };
C++ doesn’t have anonymous structs. This is ill-formed in C++.
But it relies on undefined behavior as you don’t know whether to check isHeap1 or isHeap2 until you have already accessed one of their values.
If the order of the members is flexible, then this would be a well defined alternative:
union {
struct {
bool isHeap;
size_t cap;
} s1;
struct {
bool isHeap;
char buff[15];
} s2;
};
This is the special case where accessing inactive member of union is allowed: Common initial sequence of two standard layout structs. In other words, even if s1
is the active member, reading s2.isHeap
is well defined and results in the value of s1.isHeap
and vice-versa.
CLICK HERE to find out more related problems solutions.