首页 > 解决方案 > 哪个条件语句比另一个更快 (width*height*depth == 0) OR (width ==0 || height == 0 || depth == 0)

问题描述

在计算速度很重要的算法中描述 3 维对象时,以下哪个条件表达式更快?

class Box {
    unsigned int width, height, depth;

public:
    bool isNull(){

       return (width*height*depth == 0);
       //OR
       return (width ==0 ||  height == 0 || depth == 0);
    }
};

标签: c++returnreturn-value

解决方案


return 语句中使用的表达式

return (width*height*depth == 0);

通常只是相对于第二个 return 语句中的表达式不正确。由于溢出,您可以获得等于 0 的结果,但这并不意味着其中一个操作数等于 0。

这是一个演示程序。

#include <iostream>

int main() 
{
    std::cout << 0x10000000u * 0x10000000u  * 10u << '\n';

    return 0;
}

程序输出为

0

尽管两个操作数都不等于0


推荐阅读