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

后端 未结 17 1493
一生所求
一生所求 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:14

    In C #define is much more popular. You can use those values for declaring array sizes for example:

    #define MAXLEN 5
    
    void foo(void) {
       int bar[MAXLEN];
    }
    

    ANSI C doesn't allow you to use static consts in this context as far as I know. In C++ you should avoid macros in these cases. You can write

    const int maxlen = 5;
    
    void foo() {
       int bar[maxlen];
    }
    

    and even leave out static because internal linkage is implied by const already [in C++ only].

提交回复
热议问题