While searching for an answer to the question above, I came across the answer of Luke Kowald to the question Check if a value is defined in an C enum?. It states that one can check if a value is a valid for an enum, by checking if it is equal to one of the possible values in a switch.
typedef enum {
MODE_A,
MODE_B,
MODE_C
}MODE;
int modeValid(int mode)
{
int valid = 0;
switch(mode) {
case MODE_A:
case MODE_B:
case MODE_C:
valid = 1;
};
return valid;
}
Suppose, the value int mode
has been converted to type MODE
prior to checking if it is valid:
int modeValid(MODE mode)
{
int valid = 0;
switch(mode) {
case MODE_A:
case MODE_B:
case MODE_C:
valid = 1;
};
return valid;
}
Would this still be guaranteed to work or could the compiler optimize the check into always true as the enum should never have a value other than the ones checked for?
How would this behave in case of enum classes?