【发布时间】:2017-01-12 17:57:12
【问题描述】:
所以我在谈论学习 C 语言的 lynda 课程,这个例子被展示并且几乎没有解释,所以我无法理解为什么结果是这样的。记住代码不应该是正确的,我应该明白会发生什么。
#include <stdio.h>
#define MAX(a, b) ( (a) > (b) ? (a) : (b) )
int increment() {
static int i = 42;
i += 5;
printf("increment returns %d\n", i);
return i;
}
int main( int argc, char ** argv ) {
int x = 50;
printf("max of %d and %d is %d\n", x,increment(), MAX(x, increment()));
printf("max of %d and %d is %d\n", x,increment(), MAX(x, increment()));
return 0;
}
结果是:
increment returns 47
increment returns 52
max of 50 and 52 is 50
increment returns 57
increment returns 62
increment returns 67
max of 50 and 67 is 62
有人可以向我解释为什么增量返回 47,因为如果 a 是 int x 并且 int x = 50 和 b 是 47 因为它执行 MAX(x, increment()) 。如果我没有看错代码,它应该打印 50,因为 50 大于 47。
【问题讨论】:
-
函数参数的求值顺序未指定。如果课程教导相关代码具有特定结果,我建议您在其他地方搜索知识。
-
宏的行为也不如人们预期的那样。手动将宏调用替换为内容(或获取预处理输出)并使用笔和纸处理代码。宏是不是函数。永远不要在函数可以使用的地方使用宏!
-
这样你就不会误入歧途,例如
max()和min()宏,取决于参数的类型,如果任何参数值小于0,可以/将返回错误的值。
标签: c parameter-passing function-calls