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

前端 未结 7 1199
北恋
北恋 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:03

    Are you sure your compiler is too dumb to optimize your constant by inserting its value where it is needed instead of putting it into memory? Compilers usually are good in optimizations.

    And the main advantage of constants versus macros is that constants have scope. Macros are substituted everywhere with no respect for scope or context. And it leads to really hard to understand compiler error messages.
    Also debuggers are not aware of macros.
    More can be found here

提交回复
热议问题