What are the major advantages of const versus #define for global constants?

前端 未结 7 1124
北恋
北恋 2021-01-14 10:28

In embedded programming, for example, #define GLOBAL_CONSTANT 42 is preferred to const int GLOBAL_CONSTANT = 42; for the following reasons:

7条回答
  •  孤城傲影
    2021-01-14 11:13

    In C the const qualifier does not define a constant but instead a read-only object:

    #define A  42       // A is a constant
    const int a = 42;  // a is not constant
    

    A const object cannot be used where a real constant is required, for example:

    static int bla1 = A;  // OK, A is a constant
    static int bla2 = a;  // compile error, a is not a constant
    

    Note that this is different in C++ where the const really qualifies an object as a constant.

提交回复
热议问题