0

How can you compare an enum to a uint8?

enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE }
struct Param {
    uint8 op;
}

I have a Param param; which has the enum's index saved as uint8 on param.op. Then I have seen before a comparison like so:

if (Op(param.op) == Op.NONE)

However, I didn't find any documentation about accessing an enum like it's happening here: Op(uint8variable)

If eg. enum Enum { BLA } is accessed through Enum(), what does that do exactly?

1

you can see Op(param.op) as a cast from uint8 to the enum type Op. Indeed Solidity supports explicit conversion from and to int types, but implicit conversion is not allowed that's why you need that.

if (Op(param.op) == Op.NONE) will compile, while if (param.op == Op.NONE) will not. Same if you try to convert a enum type to int

function test() public pure returns(uint8) {
    return uint8(Op.NONE); //explicit conversion allowed
    // with return Op.NONE; you will get an error at compile time 
}
2
0

Enums : Enums are one way to create a user-defined type in Solidity.

// Lets see Enums which are often used for state machine like this
enum State { Created, Locked, Inactive };

// post this a variable can be Declared like this
State public state;

// Initializing the state can be done like this
state = State.Created;

// It is important to note that enums can be explicitly converted to ints like this
uint createdState = uint(State.Locked);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.