Difference between Enum and Define Statements

后端 未结 18 2526
终归单人心
终归单人心 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 00:57

    #define is a preprocessor command, enum is in the C or C++ language.

    It is always better to use enums over #define for this kind of cases. One thing is type safety. Another one is that when you have a sequence of values you only have to give the beginning of the sequence in the enum, the other values get consecutive values.

    enum {
      ONE = 1,
      TWO,
      THREE,
      FOUR
    };
    

    instead of

    #define ONE 1
    #define TWO 2
    #define THREE 3
    #define FOUR 4
    

    As a side-note, there is still some cases where you may have to use #define (typically for some kind of macros, if you need to be able to construct an identifier that contains the constant), but that's kind of macro black magic, and very very rare to be the way to go. If you go to these extremities you probably should use a C++ template (but if you're stuck with C...).

提交回复
热议问题