This question already has answers here:
Closed last year.
Macros and postincrement
(8个答案)
我有个问题要问这个代码会打印什么。我看到答案是5,但我搞不懂为什么,++发生了什么?价值到底会增加到哪里?谢谢您!
现在通过将
旁注,上面一个是简单的三元运算符,下面是它的工作原理
首先求解
(8个答案)
我有个问题要问这个代码会打印什么。我看到答案是5,但我搞不懂为什么,++发生了什么?价值到底会增加到哪里?谢谢您!
#include <stdio.h>
#define Max(a,b) ((a>b)?a:b)
int foo(int num1, int num2)
{
return Max(num1, ++num2);
}
void main()
{
int a = 4, b = 3;
int res = foo(a, b);
printf("%d\n",res);
return 0;
}
Edit: So I tried to change the code and see if i get the point.
Now what happens after the replacement is: ((4>4++)?4:5++) so when i enter it to the parameter a it should hold the value 6 but I see that its 5 and again i cant get why. Thanks
#include <stdio.h>
#define Max(a,b) ((a>b)?a:b)
int foo(int num1, int num2)
{
int a= Max(num1, num2++);
return a;
}
void main()
{
int a = 4, b = 4;
int res = foo(a, b);
printf("%d\n",res);
return 0;
}
最佳答案
宏替换之后,foo()
函数看起来像
int foo(int num1, int num2) {
return ((num1>++num2)?num1:++num2);
}
现在通过将
num1
值视为4
和num2
值视为3
来解决下面的问题 Here num2 Here num2
become 4 becomes 5
| |
((num1 > ++num2) ? num1 : ++num2)
|
(( 4 > 4 ) ?
|
false i.e it will return ++num2 as a output & which in turns return 5
旁注,上面一个是简单的三元运算符,下面是它的工作原理
operand-1 ? operand-2 : operand-3 ;
首先求解
operand-1
,如果其结果为true(non-zero)
,operand-2
将视为输出,否则operand-3
。在您提到的代码中,返回foo()
,即operand-3
。关于c - 宏(C)中的预递增,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50762518/
10-11 15:17