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

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

    In C, specifically? In C the correct answer is: use #define (or, if appropriate, enum)

    While it is beneficial to have the scoping and typing properties of a const object, in reality const objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.

    So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int object as a case label (while a macro will work). You can't use a const int object as a bit-field width (while a macro will work). In C89/90 you can't use a const object to specify an array size (while a macro will work). Even in C99 you can't use a const object to specify an array size when you need a non-VLA array.

    If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define in C. And don't forget another alternative, that produces true constants in C - enum.

    In C++ const objects are true constants, so in C++ it is almost always better to prefer the const variant (no need for explicit static in C++ though).

提交回复
热议问题