2

Consider the following code.

//We use c++ version 98.

#include <iostream>

using namespace std;

//declaration of this enum type is in C header file.
typedef enum Color {
    Red=1, 
    Blue=11
} Color;

//Signature of this function can't be changed
int func(Color c){
    //Following line causes UndefinedBehaviour in clang++ if 
    //value is not a valid Color value
    return (int)c;
}

int main(){
    int x;
    cin >> x;
    cout << func((Color)x) << endl;
    return 0;
}

//Compilation:
//clang++ -fsanitize=undefined main.cpp

Now we want to check if value of c in func is valid and also want to avoid "Undefined behaviour". But we do not have any control over the caller of the func.

Note that the declaration of Color is in C header file.

Vimal Patel
  • 211
  • 2
  • 9
  • Does this answer your question? [How to check if enum value is valid?](https://stackoverflow.com/questions/4969233/how-to-check-if-enum-value-is-valid) – Adrian Mole Jul 14 '20 at 10:28
  • @AdrianMole No. I know which values will cause undefined behavior but I don't know how to check it in function `func`. Just even accessing enum variable `c` in `func` causes undefined behavior. – Vimal Patel Jul 14 '20 at 10:43
  • I just found a way to handle this. `int x = (int)*reinterpret_cast(&c)` then perform checks on `x`. – Vimal Patel Jul 14 '20 at 11:01
  • `std::underlying_type` can inform the type used to store the enum than, you can apply `numeric_limits<>` it will narrow the overflow cases when you are using a enum : char {}... – Cleiton Santoia Silva Jul 14 '20 at 11:18
  • 1
    _"I just found a way to handle this."_ Not a good way, since that is undefined behavior. – Eljay Jul 14 '20 at 11:34
  • @Eljay I also had that doubt. That this might cause an undefined behavior. But I was unable to detect it. :) – Vimal Patel Jul 14 '20 at 12:13
  • Isn’t it the conversion *to* `Color` that might have undefined behavior? – Davis Herring Jul 14 '20 at 17:40
  • That's one of the wonders about undefined behavior, it can sometimes appear to work. Insidious. – Eljay Jul 14 '20 at 19:52

0 Answers0