Created
November 25, 2013 19:19
-
-
Save boredzo/7647085 to your computer and use it in GitHub Desktop.
Validating an enumeration on input using switch and a warning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//So you have an enumeration that counts up to some value. | |
enum { | |
A = 1, | |
B, C, D, E, F, G, H, I, | |
J | |
}; | |
//You may be reading this enum from an input file. You'd like to check whether you have a valid value. | |
//One way would be to have a count value: | |
enum { | |
A = 1, | |
B, C, D, E, F, G, H, I, | |
J, | |
numLetters | |
}; | |
unsigned value = /*input*/; | |
if (value < numLetters) | |
valid = true; | |
else | |
valid = false; | |
//But, as @steve_holt points out, this breaks the “switch has unhandled cases” warning: any switch that handles this enum now needs to handle the numLetters case, which is not a valid case itself. | |
// https://twitter.com/steve_holt/status/405045512786554880 | |
//What you can do instead is use that very same warning: | |
valid = false; | |
switch (value): | |
case A: | |
case B: | |
case C: | |
case D: | |
case E: | |
case F: | |
case G: | |
case H: | |
case I: | |
case J: | |
valid = true; | |
} | |
//Long way around, but it does the job without breaking the warning. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment