Why would someone use #define to define constants?

前端 未结 9 1656
星月不相逢
星月不相逢 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:27

    const int is just an int that can't change. #define is a directive to the C preprocessor, which is much more than just for defining constants.

    See here for more details: http://en.wikipedia.org/wiki/C_preprocessor

    0 讨论(0)
  • 2020-11-27 04:32

    #define is necessary to make things like inclusion guards work, because C++ doesn't have a real module import system.

    #define causes a literal textual substitution. The preprocessor understands how to tokenize source code, but doesn't have any idea what any of it actually means. When you write #define sum 1, the preprocessor goes over your code and looks for every instance of the token sum and replaces it with the token 1.

    This has a variety of limitations: #define sq(x) x * x will not work right if you use it like sq(3+3); and using #define for a constant does not respect scope in any way, nor does it associate any kind of type with the constant. However, #define can be used (especially in combination with some other special stuff like the # and ## preprocessor operators) to do some magic that is otherwise not possible (except by manually doing what the preprocessor does).

    0 讨论(0)
  • 2020-11-27 04:34

    The first is a preprocessor directive, before the compiler compiles your code, it will go through and replace sum with 1. The second declares a variable in memory to hold that quantity. I'm sure it can be argued as to which is best, but the "const int" is probably more common in C++ (when it comes to numeric constants).

    http://www.geekpedia.com/KB114_What-is-the-difference-between-sharpdefine-and-const.html

    0 讨论(0)
提交回复
热议问题