Duplicated Values in C++ Enums

20:11
Mon
16
Jan 2012

Duplicated Values in C++ Enums

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_UNKNOWN,

    OP_UNARY,
    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_BINARY,
    OP_ADD = OP_BINARY, // x + y
    OP_SUB,             // x - y
    OP_MUL,             // x * y
    OP_DIV,             // x / y
    OP_MOD,             // x % y
    // ...

    OP_TERNARY,
    OP_CONDITIONAL = OP_TERNARY, // ?:

    NUM_OPS
};

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 (2) | Tags: c++

Comments

Arseny Kapoulkine
2012-01-16 23:44:31
Just for reference, the person who said that was probably this guy: http://twitter.com/#!/ID_AA_Carmack/status/154636008825167872
Reg
2012-01-17 20:46:00
Arseny Kapoulkine: Right! I forgot about that tweet. Anyway, as my example shows, I believe this feature is sometimes useful.

Post comment

Nick *
Your name or nickname
URL
URL to your homepage or e-mail address (optional)
Text *
Content of your comment
Calculate *
(* - required field)
STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2012 Adam Sawicki
Copyright © 2004-2012 Adam Sawicki