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

前端 未结 7 1183
北恋
北恋 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 10:58

    The answer to your question varies for C and C++.

    In C, const int GLOBAL_CONSTANT is not a constant in C, So the primary way to define a true constant in C is by using #define.

    In C++, One of the major advantage of using const over #define is that #defines don't respect scopes so there is no way to create a class scoped namespace. While const variables can be scoped in classes.

    Apart from that there are other subtle advantages like:

    Avoiding Weird magical numbers during compilation errors:

    If you are using #define those are replaced by the pre-processor at time of precompilation So if you receive an error during compilation, it will be confusing because the error message wont refer the macro name but the value and it will appear a sudden value, and one would waste lot of time tracking it down in code.

    Ease of Debugging:

    Also for same reasons mentioned in #2, while debugging #define would provide no help really.

提交回复
热议问题