序列返回49但应返回36

时间:2014-08-07 10:30:55

标签: c++ visual-c++ math console

以下代码旨在专门返回值36,而不是返回49,但无法查看方法或原因。任何帮助将不胜感激。

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>

#define MUL(a,b) a*b
#define ADD(a,b) a+b

static int Func1(void)
{
    static int n = 1;

    // Returns 4
    return n*++n;
}

int main()
{
    static int Incs = Func1();

    printf("%d\n", MUL(ADD(1, Incs), MUL(3, 4)));
}

2 个答案:

答案 0 :(得分:5)

我建议你检查一下预处理的输出,因为它不符合你的预期。

更确切地说:

  • ADD(1, Incs)扩展为1+Incs
  • MUL3, 4)扩展为3 * 4
  • MUL(1+Incs, 3*4)扩展为1+Incs*3*4

这就是为什么建议总是在宏中的参数周围使用括号,比如

#define MUL(a,b) ((a)*(b))

更糟糕的是Niall在评论中指出的内容,因为表达式n*++n会导致undefined behavior。未定义的行为会使整个程序格式不正确,并且会使任何输出都受到怀疑。

您应该真正阅读Niall提供的链接中接受的答案。

答案 1 :(得分:1)

让我们打破它:

MUL(ADD(1, Incs), MUL(3, 4))

由于Incs = 4,可以写成:

MUL(ADD(1, 4), MUL(3, 4))

MUL(1+4, 3*4)

1 + 4 * 3 * 4

现在编译器执行了一些BODMAS

1 + (4*3*4)

1 + 48

49

因此证明了。

哦但是你不想要这种行为,并希望每个宏分别工作 然后稍微改变你的宏定义

#define MUL(a,b) (a)*(b)
#define ADD(a,b) (a)+(b)