c++enums

error: invalid conversion from ‘int’ to enum c++


I am getting "error: invalid conversion from ‘int’ to ‘num'" when i compile the below sample code in c++. Typecasting it with enum name doesn't help.

#include <iostream>
using namespace std;
typedef enum
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
} num;

int main()
{
    num* numFlag;
    *numFlag |= static_cast<num>(NUM_TWO);
    return 0;
}

Please let me know if anyone knows how to resolve this.


Solution

  • Syntactically speaking,

    *numFlag |= static_cast<num>(NUM_TWO);
    

    is equivalent to

    *numFlag = (*numFlag | static_cast<num>(NUM_TWO));
    

    That explains the compiler warning/error. You would need to cast the result of the | operator.

    *numFlag = static_cast<num>(*numFlag | NUM_TWO);
    

    To make it work, you should use

    int main()
    {
        // Make numFlag an object instead of a pointer.
        // Initialize it.
        num numFlag = NUM_ZERO;
    
        // Perform the bitwise |
        numFlag = static_cast<num>(numFlag | NUM_TWO);
    
        return 0;
    }