Why would someone use #define to define constants?

前端 未结 9 1693
星月不相逢
星月不相逢 2020-11-27 04:02

It\'s simple question but why would someone use #define to define constants?

What\'s the difference between

#define sum 1 and const int su

9条回答
  •  感情败类
    2020-11-27 04:14

    No one should not!
    Actually, One should prefer const int sum = 1; over #define sum 1 for a number of reasons:

    Scope Based Mechanism:

    #defines don't respect scopes so there is no way to create a class scoped namespace. While const variables can be scoped in classes.


    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.


    Thus, to avoid the above situations const will be a better choice.

提交回复
热议问题