“static const” vs “#define” vs “enum”

后端 未结 17 1452
一生所求
一生所求 2020-11-21 05:45

Which one is better to use among the below statements in C?

static const int var = 5;

or

#define var 5

o

17条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 06:31

    I wrote quick test program to demonstrate one difference:

    #include 
    
    enum {ENUM_DEFINED=16};
    enum {ENUM_DEFINED=32};
    
    #define DEFINED_DEFINED 16
    #define DEFINED_DEFINED 32
    
    int main(int argc, char *argv[]) {
    
       printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);
    
       return(0);
    }
    

    This compiles with these errors and warnings:

    main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
    enum {ENUM_DEFINED=32};
          ^
    main.c:5:7: note: previous definition is here
    enum {ENUM_DEFINED=16};
          ^
    main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
    #define DEFINED_DEFINED 32
            ^
    main.c:8:9: note: previous definition is here
    #define DEFINED_DEFINED 16
            ^
    

    Note that enum gives an error when define gives a warning.

提交回复
热议问题