[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Thu Feb 1 11:16:55 PST 2024


AaronBallman wrote:

The rules between C and C++ aren't quite the same. C prohibits auto-increment from changing from signed to unsigned. C23 6.7.2.2p12:

> A signed integer type is chosen if the previous enumeration constant being added is of signed
> integer type. An unsigned integer type is chosen if the previous enumeration constant is of
> unsigned integer type. If there is no suitably sized integer type described previously which
> can represent the new value, then the enumeration has no type which can represent all its
> values.

whereas C++ allows changing from signed to unsigned. C++23 [enum]p5:

> Otherwise the type of the enumerator is the same as that of the preceding enumerator unless the incremented value is not representable in that type, in which case the type is an unspecified integral type sufficient to contain the incremented value. If no such type exists, the program is ill-formed.

Curiously though, GCC seems to implement the rules backwards from what I'd expect: https://godbolt.org/z/abGvj9Tn4 but that might be for backwards compatibility as they do that in C17 mode as well.

One interesting thing to test is `-pedantic` mode to make sure we don't get this: https://godbolt.org/z/K4K1E3GEx

https://github.com/llvm/llvm-project/pull/78742


More information about the cfe-commits mailing list