mardi 20 juillet 2021

C++ int to enum class UB

I have a enum which looks like this:

enum class MY_TYPE : int32_t{
    UNKNOWN = 0,
    A = 101,
    B = 102,
    C = 103,
    D = 104,
    E = 105
};

and I want to cast given values from and to it. First of all, is it guaranteed that this does not induce undefined behaviour:

void library_func(int* tp){ *tp = 275;}


int main(){
    MY_TYPE d = static_cast<MY_TYPE>(224);
    library_func(reinterpret_cast<int*>(&d));

    std::cout << "d is " << static_cast<int>(d);

}

Is it UB if I try and cast a value not inside the value range of MY_TYPE? About this I found the following issue: stackoverflow

This prints 275 as expected. Do I understand the answer correctly that casting any value which fits in the enums underlying type is fine?

Aucun commentaire:

Enregistrer un commentaire