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

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

    It is ALWAYS preferable to use const, instead of #define. That's because const is treated by the compiler and #define by the preprocessor. It is like #define itself is not part of the code (roughly speaking).

    Example:

    #define PI 3.1416
    

    The symbolic name PI may never be seen by compilers; it may be removed by the preprocessor before the source code even gets to a compiler. As a result, the name PI may not get entered into the symbol table. This can be confusing if you get an error during compilation involving the use of the constant, because the error message may refer to 3.1416, not PI. If PI were defined in a header file you didn’t write, you’d have no idea where that 3.1416 came from.

    This problem can also crop up in a symbolic debugger, because, again, the name you’re programming with may not be in the symbol table.

    Solution:

    const double PI = 3.1416; //or static const...
    

提交回复
热议问题