宏观预增量(C)

时间:2018-06-08 14:09:55

标签: c macros

我对这段代码打印的问题提出了疑问。我看到答案是5但我无法弄清楚为什么,++会发生什么?价值会在哪里增加?谢谢!

        #include <stdio.h>
        #define Max(a,b) ((a>b)?a:b)
        int foo(int num1, int num2)
        {
            return Max(num1, ++num2);
        }
        void main()
        {
            int a = 4, b = 3;
            int res = foo(a, b);
            printf("%d\n",res);
            return 0;
        }

    Edit: So I tried to change the code and see if i get the point.
Now what happens after the replacement is: ((4>4++)?4:5++) so when i enter it to the parameter a it should hold the value 6 but I see that its 5 and again i cant get why. Thanks
    #include <stdio.h>
    #define Max(a,b) ((a>b)?a:b)
    int foo(int num1, int num2)
    {
        int a= Max(num1, num2++);
        return a;
    }
    void main()
    {
        int a = 4, b = 4;
        int res = foo(a, b);
        printf("%d\n",res);
        return 0;
    }

3 个答案:

答案 0 :(得分:1)

宏通过文本替换工作,所以在你的情况下

Max(num1, ++num2)
在实际编译发生之前,

将被以下代码替换:

((num1 > ++num2) ? num1 : ++num2)

现在你应该能够弄清楚自己发生了什么。

答案 1 :(得分:1)

使用宏来对更大的值进行排序。因此,您的参数++num2会替换宏中的b并提供生成的代码:

((num1 > ++num2) ? num1 : ++num2);

条件为假,因为num1 = 4num2 = 4,因此您的三元运算符的第二部分会再次处理...... ++num2 !! 最后b = 5

有关详细信息,请参阅此帖子:Macros and postincrement

答案 2 :(得分:1)

宏替换后,foo()函数看起来像

int foo(int num1, int num2) {
    return ((num1>++num2)?num1:++num2);
}

现在通过将num1值视为4并将num2值视为3

来解决以下问题
     Here num2            Here num2
      become 4             becomes 5 
        |                   | 
((num1 > ++num2) ?  num1 :  ++num2)
   |      
(( 4   >   4 )   ?
       |
    false i.e it will return ++num2 as a output & which in turns return 5

旁注,上面是一个简单的三元运算符&amp;这是它的工作原理

operand-1 ?  operand-2 : operand-3 ;

首先解析operand-1,如果结果为true(non-zero),则operand-2将视为输出operand-3。在您提到的代码foo()中,返回operand-3 5

相关问题