代码之家  ›  专栏  ›  技术社区  ›  Primemaster

条件分支求值

  •  -1
  • Primemaster  · 技术社区  · 5 年前
    const int IX(int x, int y, std::size_t width)
    {
        if ((width * y + x) > 0)
        {
            return width * y + x;
        }
        else
        {
            return 0;
        }
    }
    
    const int IX(int x, int y, std::size_t width)
    {
        int value = width * y + x;
        if (value > 0)
        {
            return value;
        }
        else
        {
            return 0;
        }
    }
    

    在这里如果 x=0 y=-1 独立于 width 我使用visual studio 2019编译器。

    1 回复  |  直到 5 年前
        1
  •  1
  •   SergeyA    5 年前

    这是一个很好的例子,展示了除了非常窄的域(即位操作)之外,如何去除无符号类型。

    (width * y)
    

    既然如此 width size_t )其结果也是无符号的(在您的例子中,是相当大的值),因此,总是大于或等于零。

    int i = width * y
    

    结果,它再次被签名,现在小于0。