Duplicated Values in C++ Enums

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Jan 2012

There is a feature in C++ and other programming languages that allows assigning particular numeric values to elements in enums, even same values to many elements. I've recently heard somebody telling that it is completely useless. I can't agree with that. Let me give an example from the source of the scripting language I recently code at home. Enum representing language operators makes use of the order of numeric values to easily determine the number of arguments for each operator. I've defined special elements in this enum to mark the beginning of operators that take one, two or three arguments.

enum OP

    OP_NEG = OP_UNARY, // -x
    OP_BIT_NOT,        // ~x
    OP_LOG_NOT,        // !x
    OP_PRE_INC,        // ++x
    OP_PRE_DEC,        // --x
    OP_POST_INC,       // x++
    OP_POST_DEC,       // x--
    // ...

    OP_ADD = OP_BINARY, // x + y
    OP_SUB,             // x - y
    OP_MUL,             // x * y
    OP_DIV,             // x / y
    OP_MOD,             // x % y
    // ...



uint GetOpNumArguments(OP op)
    if (op == OP_UNKNOWN) return 0;
    else if (op < OP_BINARY)  return 1;
    else if (op < OP_TERNARY) return 2;
    else if (op < NUM_OPS)    return 3;
    else return 0;

Comments | #c++ Share


[Download] [Dropbox] [pub] [Mirror] [Privacy policy]
Copyright © 2004-2019