Yksisarvinen
Yksisarvinen

Reputation: 22304

Forcing invalid value to enum with C++17

In our project, enums are commonly used for communication with other components. This is old code, so C++ unscoped enumerations with non fixed type are mostly used.

For the purpose of UT, we would like to test the situation, when we receive invalid value of enum (it comes from different components, so we can't be 100% it'll be correct). Everything is fine, when enum has some 'empty' values - values, which are not used, but still in valid range. But let's consider following enumeration:

enum Foo {
    Foo_A,
    Foo_B,
    Foo_C,
    Foo_D
}

According to C++17 standard, we can static_cast values 0-3, and any other invokes Undefined Behaviour.

What if we need to pass the value from outside valid range? I want to check, if my function reacts correctly (returning error) when passed value e.g. 4.

What can be done to avoid UB and still test possible invalid enum values?

Note: We can use fixed underlying type for some enums, but we don't control everything. Some enums are provided by other components that we work with, and forcing a change in every component will be rather difficult. Few nasal demons are probably easier to deal with.

Upvotes: 3

Views: 1242

Answers (1)

MSalters
MSalters

Reputation: 179927

The problem here is that the range of "Undefined Behavior" includes "works without any noticeable abnormalities". You can't test if Undefined Behavior occurred.

Instead, you'll need to write a manual check that the value before casting is >=Foo_A and <= Foo_D

Upvotes: 2

Related Questions