C++ Logo


Advanced search

Re: Reasoning for strict aliasing enums from underlying type

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 10 May 2022 17:50:30 -0400
On Tue, May 10, 2022 at 5:09 PM Myria via Std-Discussion
<std-discussion_at_[hidden]> wrote:
> What is the reasoning behind C++'s type aliasing rules prohibiting
> accessing an enum through a pointer to its underlying type? This
> differs from C and feels counter-intuitive when C++ does allow
> accessing an int from an unsigned pointer.
> enum Kitty { KITTY };
> enum Kitty Test(enum Kitty* x, int* y)
> {
> *x = KITTY;
> *y = -1;
> return *x;
> }
> This works in C when x and y alias, returning (Kitty) -1, but in C++
> is undefined behavior.

I don't know what the rule is in C, but in C++, implementations are
free to make `Kitty` have an underlying type of `short`. Or `char`. So
this is not required to work in C++ *regardless* of the rules relating
to underlying types.

A good reason not to allow this is that it would potentially break
existing optimization opportunities. In the above code, the compiler
can assume that `*y` has no effect on `*x` and make optimizations
based on that.

Received on 2022-05-10 21:51:11