Enums and binary or operator (MISRA C++ 2008, 4-5-2)

Viewed 517

MISRA C++ 2008, 4-5-2 states: Expressions with type enum shall not be used as operands to built-in operators other than the subscript operator [ ], the assignment operator =, the equality operators == and !=, the unary & operator, and the relational operators <, <=, >, >=.

If one can use & why it is not allowed to use binary | with enums?

2 Answers

You're making a false comparison.

Unary & is the "address-of" operator, and has no relationship to the binary & "and" operator.

The MISRA rules have prohibited all bitwise operations on enumerations, while continuing to permit taking the address of an object of such a type.

As pointed out in another answer, you are mixing up binary & with unary &.

The reason why you can't use binary | and other bitwise operators on enums is that enumerated types (variables of enum type) have implementation-defined size and signedness. And enumeration constants (the values in the enumeration list) always have type signed int.

In either case, using any form of bitwise operations on signed numbers is always problematic: you can get unexpected results or invoke poorly-defined behavior. This is the main problem that the rule seeks to prevent.

MISRA also banned regular arithmetic with the same rationale: don't do arithmetic on a type which you don't know the size and signedness of. Not as likely to cause bugs, but I guess there's a place for it if you do weird stuff like enum { X=30000 }; ... X + X. Is this well-defined, or an implicit promotion to int, or undefined because of integer overflow? It could be either of these cases and it isn't necessarily tied to the CPU data size.

Related