Doesn't static_cast
protect against 'invalid' values to the type it's being cast to i.e Values
here?
If so, it's not a good idea to print the casted value? How to ensure the print only takes place once the value is correct/valid?
enum class Values : uint8_t
{
One,
Two
};
void bar(uint8_t value)
{
Values val = static_cast<Values >(value);
printf ("The received value = %u\n", val);
switch(val)
{
case One: break;
case Two: break;
default: break;
}
}
int main()
{
bar(static_cast<uint8_t>(60));
}
Seemingly static_cast
doesn't protect against 'invalid' values so in this snippet, how should the verification be done? Something like following or there's a better way?
enum class Values : uint8_t
{
One,
Two,
Max
};
void bar(uint8_t value)
{
Values val = static_cast<Values>(value);
if (val < Values::Max)
printf ("The received value = %u\n", val);
switch(val)
{
case One: break;
case Two: break;
default: printf ("invalid value!"); break;
}
}