r/cpp • u/pavel_v • Mar 07 '26
Accessing inactive union members through char: the aliasing rule you didn’t know about
https://www.sandordargo.com/blog/2026/03/04/char-representation-and-UB
34
Upvotes
35
u/AKostur Mar 07 '26
Because we’re being picky: the representation of a bool is not guaranteed by the standard to be the bit representation of 0 or 1. Thus it is theoretically possible that true is represented by the bit representation of 2.
36
u/38thTimesACharm Mar 07 '26
I don't really like this justification. It's true the cited rule, about strict aliasing violations being UB, has an exception for
char. So we conclude the rule doesn't apply in this case.However, that doesn't mean the behavior is defined. It just means it isn't undefined as a result of this particular rule.
But there are other rules! I don't feel like going through the whole standard right now, but if there's a different rule that says "accessing inactive member of union is UB," and that rule doesn't contain the same exception, then the exception for the strict aliasing rule doesn't cancel that out.
It's a moot point in this case, because no compiler is ever going to generate bad code here. They would have to be actively malicious, sacrificing performance for the sake of breaking your program. But the reasoning in the post seems logically invalid and dangerous to me.
4
u/silajim Mar 07 '26
This thing gets used from time to time when working with the win32 api
2
u/Business_Welcome_870 Mar 07 '26
Cool
1
u/phi_rus Mar 07 '26
It's cool. But if it looks like it could be UB, I don't want it in my codebase. So I won't use this.
1
u/Paradox_84_ Mar 08 '26
I wish we stopped doing that and only allow such things for std::byte, but that won't happen. We'll just cary this baggage till 2475 probably
0
u/chibuku_chauya Mar 07 '26
Shocking and dangerous.