目录

c表达式执行顺序的问题

目录

c++表达式执行顺序的问题

#include <iostream>
#include <cstdio>
#include <cstdint>

typedef std::uint8_t CostType;

int main()
{
    int width = 450, height = 375, xstep = 4, ystep = 4, dMax = 128;
    printf("sizeof(size_t)=%d\n\n", sizeof(size_t));

    printf("=====method1:\n");
    printf("final size: %zu\n\n", static_cast<size_t>(width + xstep - 1) / xstep *
        (height + ystep - 1) / ystep * dMax * sizeof(CostType));


    printf("=====method2:\n");
    size_t outputWidth = (width + xstep - 1) / xstep;
    size_t outputHeight = (height + ystep - 1) / ystep;
    size_t totalSize = outputWidth * outputHeight * dMax * sizeof(CostType);
    printf("Step by step: %zu * %zu * %d * %zu = %zu\n\n",
        outputWidth, outputHeight, dMax, sizeof(CostType), totalSize);


    printf("=====method3:\n");
    size_t step1 = static_cast<size_t>(width + xstep - 1) / xstep;
    size_t step2 = (height + ystep - 1) / ystep;
    size_t step3 = step1 * step2;
    size_t step4 = step3 * dMax;
    size_t finalSize = step4 * sizeof(CostType);
    printf("Step 1: %zu\n", step1);
    printf("Step 2: %zu\n", step2);
    printf("Step 3: %zu\n", step3);
    printf("Step 4: %zu\n", step4);
    printf("Final Size: %zu\n\n", finalSize);


    printf("=====method4:\n");
    printf("final size: %zu\n",
        (((static_cast<size_t>(width + xstep - 1) / xstep) *
            ((static_cast<size_t>(height + ystep - 1) / ystep))) *
            static_cast<size_t>(dMax)) * sizeof(CostType));
}

输出为:

sizeof(size_t)=8

=====method1:

final size: 1366784

=====method2:

Step by step: 113 * 94 * 128 * 1 = 1359616

=====method3:

Step 1: 113

Step 2: 94

Step 3: 10622

Step 4: 1359616

Final Size: 1359616

=====method4:

final size: 1359616

Method1 和method2的结果不一致,看起来是由于计算顺序导致的,但是按照C++标准,method1和method2的计算顺序应该是完全一致的才对,结果也应该是完全相同的才对,但就如method4看到的那样,多加一个括号来强制保证计算顺序和method2的结果就一致了。

编译器:vs2019和gcc5.2.0的结果一致,都是上述的结果。