Difference between Enum and Define Statements

后端 未结 18 2527
终归单人心
终归单人心 2020-11-30 00:27

What\'s the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?

For exampl

18条回答
  •  攒了一身酷
    2020-11-30 01:14

    Another advantage of an enum over a list of defines is that compilers (gcc at least) can generate a warning when not all values are checked in a switch statement. For example:

    enum {
        STATE_ONE,
        STATE_TWO,
        STATE_THREE
    };
    
    ...
    
    switch (state) {
    case STATE_ONE:
        handle_state_one();
        break;
    case STATE_TWO:
        handle_state_two();
        break;
    };
    

    In the previous code, the compiler is able to generate a warning that not all values of the enum are handled in the switch. If the states were done as #define's, this would not be the case.

提交回复
热议问题