【发布时间】:2014-11-07 23:11:31
【问题描述】:
我编写了一小段代码,其中我使用了#define 和增量运算符。代码是
#include <stdio.h>
#define square(a) ((a)*(a))
int main ()
{
int num , res ;
scanf ("%d",&num ) ;
res = square ( num++ ) ;
printf ( "The result is %d.\n", res ) ;
return 0 ;
}
但在 gcc 中编译时,我收到以下注释和警告:
defineTest.c:8:20: warning: multiple unsequenced modifications to 'num' [-Wunsequenced]
res = square ( num++ ) ;
^~
defineTest.c:2:21: note: expanded from macro 'square'
#define square(a) ((a)*(a))
^
1 warning generated.
请解释警告和注意事项。 我得到的输出是:
$ ./a.out
1
结果是 2。$ ./a.out
2
结果是 6。
同时解释代码的工作原理。
【问题讨论】:
-
您的
res变为res = ((num++)*(num++)) ;阅读:stackoverflow.com/q/4176328/1870232 -
你想用
square(num++)实现什么 -
调用未定义的行为——也许是关于该主题的第千个问题。唯一的边缘新奇是预处理器的使用,但结果与所有其他的完全相同。
-
@P0W:C++ 问题并不是指导 C 程序员的最佳方式。
-
我的口头禅:几乎总是避免使用宏。 (AAAM)
标签: c c-preprocessor pre-increment