在c中定义为#的前/后增量

在c中定义为#的前/后增量,c,c-preprocessor,pre-increment,C,C Preprocessor,Pre Increment,我编写了一小段代码,其中使用了#define with increment操作符。代码是 #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

我编写了一小段代码,其中使用了#define with increment操作符。代码是

#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 ;
}
请解释警告和注意事项。 我得到的结果是:

美元/a.out
1
结果是2

美元/a.out
2
结果是6


还要解释代码的工作原理。

预处理器展开宏后,宏的外观如下所示:

((a++)*(a++))
请注意,
a++
a=a+1
相同,因此可以将扩展宏重写为:

((a = a + 1)*(a = a + 1))
您在一条语句中两次更改
a
(确切地说是
num
)的值,这会生成警告,因为这是未定义的行为

我建议您将宏重写为函数

int square(int x)
{
    return x*x;
}

你的
res
变成
res=((num++)*(num++))阅读以下内容:使用
square(num++)
调用未定义的行为,您希望实现什么?这可能是本主题的第一千个问题。唯一的边缘新颖之处是使用预处理器,但结果与其他所有的结果完全一样。@ P0W:C++问题不是指导C程序员的最好方法。我的口头禅:几乎总是避免宏。(AAAM)
int square(int x)
{
    return x*x;
}