#define与运算符一起使用 [英] #define used with operators
问题描述
我知道 #define
具有以下语法: #define SYMBOL字符串
例如,如果我写
I know that #define
has the following syntax: #define SYMBOL string
If I write, for example
#define ALPHA 2-1
#define BETA ALPHA*2
然后 ALPHA = 1
但 BETA = 0
.(为什么?)
但是如果我写这样的话
#define ALPHA (2-1)
#define BETA ALPHA*2
然后 ALPHA = 1
和 BETA = 2
.
有人可以解释一下这两者之间有什么区别吗?
Can someone explain me what's the difference between those two ?
推荐答案
使用 #define
创建的预处理器宏是 text 替换.
Pre-processor macros created using #define
are textual substitutions.
这两个示例并不等效.第一个将 BETA
设置为 2-1 * 2
.第二个将 BETA
设置为(2-1)* 2
.像您一样声称 ALPHA == 1
是不正确的,因为 ALPHA
不是数字-它是免费的伙计!这只是一个字符序列.
The two examples are not equivalent. The first sets BETA
to 2-1*2
. The second sets BETA
to (2-1)*2
. It is not correct to claim that ALPHA == 1
as you do, because ALPHA
is not a number - it is a free man! it's just a sequence of characters.
当解析为C或C ++时,这两个表达式是不同的(第一个与 2-(1 * 2)
相同)
When parsed as C or C++, those two expressions are different (the first is the same as 2 - (1*2)
).
我们可以通过打印 BETA
的字符串扩展并将其评估为表达式来显示差异:
We can show the difference, by printing the string expansion of BETA
as well as evaluating it as an expression:
#ifdef PARENS
#define ALPHA (2-1)
#else
#define ALPHA 2-1
#endif
#define BETA ALPHA*2
#define str(x) str2(x)
#define str2(x) #x
#include <stdio.h>
int main()
{
printf("%s = %d\n", str(BETA), BETA);
return 0;
}
在定义和不定义 PARENS
的情况下编译以上内容,以查看两者的区别:
Compile the above with and without PARENS
defined to see the difference:
(2-1)*2 = 2
2-1*2 = 0
其结果是,当使用 #define
创建扩展为表达式的宏时,通常最好使用比通常所需更多的括号,因为您不知道您的价值观将得到扩展的背景.例如:
The consequence of this is that when using #define
to create macros that expand to expressions, it's generally a good idea to use many more parentheses than you would normally need, as you don't know the context in which your values will be expanded. For example:
#define ALPHA (2-1)
#define BETA ((ALPHA)*2)
这篇关于#define与运算符一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!