断言unsigned int确实是正面的不起作用?

JAN*_*JAN 4 c++ unsigned assert unsigned-integer

我想将两个数字相乘,我知道我的数字总是正数,然后:

unsigned int mulPositiveNumbers(unsigned int a ,unsigned int b)
{
    assert(a > 0);
    assert(b > 0);
    return (a*b);
}
Run Code Online (Sandbox Code Playgroud)

现在,我正在使用断言告诉自己"给定的数字总是积极的".

但是当我跑步时:

int main()
{

    unsigned int res = mulPositiveNumbers(-4,3);

        // more stuff goes here

}
Run Code Online (Sandbox Code Playgroud)

代码不会失败,即使我使用的是负数.为什么?

sep*_*p2k 7

因为a并且b是无符号的,所以它们永远不会是负面的.断言失败的唯一方法是其中一个为0.

当您使用signed int作为参数调用函数时,它将在函数执行之前简单地转换为unsigned(因此在检查断言之前).将负整数转换为无符号将产生正整数,因为正如我所说,没有负无符号整数.