简体   繁体   English

使用定义和变量之间的区别

[英]Difference between using define and variable

If I have the code below: 如果我有以下代码:

#define POUND_PER_DOLLAR  73
int nPound = 4 * POUND_PER_DOLLAR;

AND

int POUND_PER_DOLLAR = 122;
int nPound = 4 * POUND_PER_DOLLAR;

Are there instances where usage of one is more suited than the other? 是否存在使用某一种方法比使用另一种方法更合适的情况?

If you need the address, you need a variable: 如果需要地址,则需要一个变量:

void foo(int *);

foo(&POUND_PER_DOLLAR);         // must be an lvalue

If you need a constant expression, a macro (or at least a constant) will work: 如果您需要一个常量表达式,则可以使用一个宏(或至少一个常量):

char array[POUND_PER_DOLLAR];   // must be a constant expression

However, the most appropriate construction is probably a constant: 但是,最合适的构造可能是一个常量:

const int kPoundPerDollar = 73;
int nPound = 4 * kPoundPerDollar;

void bar(const int *);
bar(&kPoundPerDollar);                 // works
char c[kPoundPerDollar];               // also works

template <const int * P> struct X {};
X<&kPoundPerDollar> x;                 // also works

Neither. 都不行 The #define is not type-safe, the int is non-const. #define不是类型安全的, int是非常量的。 This is the constant you're looking for : 这是您要寻找的常数:

int const POUND_PER_DOLLAR = 122;
#define identifier replacement

When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. 当预处理器遇到此指令时,它将通过替换替换代码其余部分中所有出现的标识符。 This replacement can be an expression, a statement, a block or simply anything. 该替换可以是表达式,语句,块或任何其他内容。 The preprocessor does not understand C++ proper, it simply replaces any occurrence of identifier by replacement. 预处理器无法正确理解C ++,它只是通过替换来替换出现的任何标识符。

Disadvantages of using #define: method, 使用#define:方法的缺点

  1. the preprocessor does not understand any c++, it only replaces it, so you are taking your own risk 预处理器不了解任何c ++,只会替换它,因此您要承担自己的风险
  2. It makes it harder for debugging, if you are using a debugger and you want to check the values of your variables 如果使用调试器,并且要检查变量的值,则调试起来会更困难
  3. You Have to be careful of redefinition of your macro 您必须小心重新定义宏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM