GCC 和 VC++ 中的宏
Macro in GCC and VC++
我在 VC++ 和 GCC 中编译了这段代码,它们产生了不同的输出,如果有人能指出我哪里出了问题,我将不胜感激。
#include "stdio.h"
#define Cube(x) x*x*x
int main(void){
int x=5;
printf("%d\r\n", Cube(x++));
return 0;
}
在 GCC 中,显示值为 210 (=5*6*7),在 VC++2010 中为 125 (=5*5*5)。
如果我这样做,
#include "stdio.h"
#define Cube(x) x*x*x
int main(void){
int x=5;
printf("%d\r\n", Cube(++x));
return 0;
}
VC++ 打印 512 (=8*8*8) 而 GCC 打印 392 (=7*7*8).
如果有人能说说发生了什么,我将不胜感激。
行
printf("%d\r\n", Cube(x++));
被预处理为:
printf("%d\r\n", x++*x++*x++));
这是导致未定义行为的原因。
printf("%d\r\n", ++x*++x*++x));
也是未定义行为的原因。
见
Why the output of this program is 41? is it undefined behavior?
Why are these constructs (using ++) undefined behavior?
您可以通过将 Cube
转换为函数来避免此问题。下面的程序运行良好。
#include "stdio.h"
int Cube(int x)
{
return x*x*x;
}
int main(void)
{
int x=5;
printf("%d\r\n", Cube(x++));
printf("%d\r\n", Cube(++x));
return 0;
}
我在 VC++ 和 GCC 中编译了这段代码,它们产生了不同的输出,如果有人能指出我哪里出了问题,我将不胜感激。
#include "stdio.h"
#define Cube(x) x*x*x
int main(void){
int x=5;
printf("%d\r\n", Cube(x++));
return 0;
}
在 GCC 中,显示值为 210 (=5*6*7),在 VC++2010 中为 125 (=5*5*5)。
如果我这样做,
#include "stdio.h"
#define Cube(x) x*x*x
int main(void){
int x=5;
printf("%d\r\n", Cube(++x));
return 0;
}
VC++ 打印 512 (=8*8*8) 而 GCC 打印 392 (=7*7*8).
如果有人能说说发生了什么,我将不胜感激。
行
printf("%d\r\n", Cube(x++));
被预处理为:
printf("%d\r\n", x++*x++*x++));
这是导致未定义行为的原因。
printf("%d\r\n", ++x*++x*++x));
也是未定义行为的原因。
见
Why the output of this program is 41? is it undefined behavior?
Why are these constructs (using ++) undefined behavior?
您可以通过将 Cube
转换为函数来避免此问题。下面的程序运行良好。
#include "stdio.h"
int Cube(int x)
{
return x*x*x;
}
int main(void)
{
int x=5;
printf("%d\r\n", Cube(x++));
printf("%d\r\n", Cube(++x));
return 0;
}