c++ - 断言 unsigned int a indeed positive 不起作用?

标签 c++ assert unsigned unsigned-integer

我想将两个数相乘,并且我知道我的数总是正数,那么:

unsigned int mulPositiveNumbers(unsigned int a ,unsigned int b)
{
    assert(a > 0);
    assert(b > 0);
    return (a*b);
}

现在,我正在使用断言告诉自己“给定的数字总是正数”。

但是当我运行时:

int main()
{

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

        // more stuff goes here

}

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

最佳答案

因为 ab 是无符号的,所以它们永远不会是负数。断言失败的唯一方法是其中之一为 0。

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

关于c++ - 断言 unsigned int a indeed positive 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12175272/

相关文章:

c++ - 如果我已经创建了结构数组初始化的构造函数,通过什么调用方法?

c++ - 如何迭代以一对为键的 map ?

Arduino 无符号长溢出

c++ - 具有数组或 vector 参数的类模板

c++ - 函数 "was not declared in this scope"

c++ - #define NDEBUG 似乎不起作用

javascript - 是否可以测试 javascript 函数是否是构造函数?

c++ - 类模板参数的static_assert

c - 未签名和已签名的扩展

python - 使用 struct.pack