Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

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.

like image 676
Scarlet Avatar asked Mar 17 '26 07:03

Scarlet


2 Answers

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;
}
like image 75
R Sahu Avatar answered Mar 19 '26 21:03

R Sahu


If you insist on doing this, at least wrap the ugliness up in an operator, so the rest of the code can be written at least reasonably cleanly:

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

num &operator|=(num &a, num const &b) {
    a = static_cast<num>(a | b);
    return a;
}

int main()
{
    num numFlag;
    numFlag |= NUM_TWO;
}

But keep in mind that this will let you generate values that aren't in your enumeration. For example, a sequence like:

num a{NUM_ZERO};
a |= NUM_TWO;
a |= NUM_THREE;

...gives a a value that's not in the enumeration.

like image 33
Jerry Coffin Avatar answered Mar 19 '26 19:03

Jerry Coffin