#define func(x,y)x + y / x

时间:2017-08-03 16:10:12

标签: c macros c-preprocessor

#include <stdio.h>
#define func(x, y) x + y/x
int main() {
    int i = -1, j = 2, x;
    printf("i = %d\n", i);
    printf("j = %d\n", j);
    printf("x = %d\n", x);
    x = func(i + j, 3);
    printf("%d\n",x);
    return 0;
}

在上面的C代码中,输出为0,而我期望为4. ie

i + j = -1 + 2 = 1   
func(i+j, 3) = func (1,3) = 1 + 3/1 = 1 + 3 = 4.   

我哪里错了?我将在哪里了解更多信息 C预处理器宏行为?

以上代码的输出如下:

Output Console

1 个答案:

答案 0 :(得分:3)

变化

#define func(x, y) x + y/x

#define func(x, y) ((x) + (y)/(x))

原因:

func(x, y) x + y/x  
x = i + j
y = 3
func(x, y) = func(i + j, 3)
=  x + y/x
=  i + j + 3/i + j
= -1 + 2 + 3/(-1) + 2
=  1 - 3 + 2
=  0