【问题标题】:I need explanation for the output of given snippet我需要解释给定片段的输出
【发布时间】:2018-09-25 14:04:22
【问题描述】:
#include<stdio.h>
#define CUBE(X)  (X*X*X)

int main(void) 
{
    int a = 2;
    int result = 0;
    result = CUBE(++a) / (++a);
    printf("\na=%d\nresult=%d", a, result);
    return 0;
}

我了解变量 a 的值如何变为 6,但我无法理解变量 result 的值如何变为 13。

【问题讨论】:

    标签: c++ computer-science


    【解决方案1】:

    编译器会将单词 CUBE 替换为 (X * X * X)。因此,代码会变成

    result = (++a * ++a * ++a) / (++a);
    //you might think result = (3 * 4 * 5) / 6;
    

    看起来结果应该是 10,但是在乘法之前应用了预增量。所以它被评估为

    result = (((++a) * (++a)) * ++a) / (++a);
    //a is incremented to 3 and then four, before the first multiplication
    
    result = ((4 * 4) * 5) / 6;
    

    结果 = 13.3333

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多