C++ Logo

std-discussion

Advanced search

Reasoning for strict aliasing enums from underlying type

From: Myria <myriachan_at_[hidden]>
Date: Tue, 10 May 2022 14:09:35 -0700
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. Clang even enforces this rule difference
between C++ as shown in its assembly output:

https://gcc.godbolt.org/z/xqanYjs4j

Loosening the restriction would also delete a bunch of mentions of
std::byte from the Standard, because std::byte would get its magic
properties from its underlying type instead of by commandment.

Melissa

Received on 2022-05-10 21:09:50