DEV Community

Enums and Exhaustive switch statements in C++

Pawel Kadluczka on December 09, 2023

Exhaustive switch statements are switch statements that do not have the default case because all possible values of the type in question have been ...
Collapse
 
pauljlucas profile image
Paul J. Lucas • Edited

There's nothing special about scoped enums or C++ insofar as switch is concerned. Everything you said applies equally well to unscoped enums in both C++ and C.

FYI, see here and here.

Collapse
 
moozzyk profile image
Pawel Kadluczka

Fair point. Having said that, except for legacy code, there are not many scenarios where I would prefer unscoped enums over scoped enums in C++.

Collapse
 
pauljlucas profile image
Paul J. Lucas

Sure, but your whole point was about exhaustive switch statements that don't care about whether enums are scoped or not.

Thread Thread
 
moozzyk profile image
Pawel Kadluczka • Edited

Until you mentioned, I incorrectly assumed that exhaustive switch statements worked only with scoped enum types. Thank you for making me aware that it is not the case. I updated the post to remove the reference to scoped enum types.

btw. your posts about C++ are incredibly comprehensive!

Thread Thread
 
pauljlucas profile image
Paul J. Lucas

The warnings are about compiler quality-of-implementation. They have nothing to do with what either the C or C++ standards mandate.

your posts about C++ are incredibly comprehensive!

I feel that anything less does a disservice to the reader. Even if there were a case where I didn't want to discuss a particular facet of something, I'd at least mention it so the reader knows its exists and can look elsewhere for more information.

Thread Thread
 
pauljlucas profile image
Paul J. Lucas

After your change, you might consider mentioning that exhaustive switch statements apply to unscoped enumerations as well — and also apply in C.

Thread Thread
 
moozzyk profile image
Pawel Kadluczka

I changed the first paragraph to call out that exhaustive switch statement can be used for both, scoped and unscoped enum types. I think I will skip the C part.

Collapse
 
pgradot profile image
Pierre Gradot

It's worth mentioning that this is true only for Clang.

With GCC, the first code raises a warning (warning: control reaches end of non-void function [-Wreturn-type]) and the option -Wswitch-enum must be added if you want to be warned when a new value is added to the enum.

See here

Collapse
 
moozzyk profile image
Pawel Kadluczka

Thanks for pointing this out! I updated the post to include this information.

Collapse
 
pgradot profile image
Pierre Gradot

To be honest, Clang behavior seems much better to me 😅

Thread Thread
 
moozzyk profile image
Pawel Kadluczka

Agree. There is no world I wouldn't want to have this switch on.