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

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

    #define var 5 will cause you trouble if you have things like mystruct.var.

    For example,

    struct mystruct {
        int var;
    };
    
    #define var 5
    
    int main() {
        struct mystruct foo;
        foo.var = 1;
        return 0;
    }
    

    The preprocessor will replace it and the code won't compile. For this reason, traditional coding style suggest all constant #defines uses capital letters to avoid conflict.

提交回复
热议问题