[英]Assert that unsigned int a indeed positive doesn't work ?
I want to multiply two numbers , and I know that my numbers are always positive , then : 我想将两个数字相乘,我知道我的数字总是正数,然后:
unsigned int mulPositiveNumbers(unsigned int a ,unsigned int b)
{
assert(a > 0);
assert(b > 0);
return (a*b);
}
Now ,I'm using assert to tell myself that "the given numbers are always positive" . 现在,我正在使用断言告诉自己“给定的数字总是积极的”。
But when I run : 但是当我跑步时:
int main()
{
unsigned int res = mulPositiveNumbers(-4,3);
// more stuff goes here
}
The code doesn't fail , even though that I'm using a negative number . 代码不会失败,即使我使用的是负数。 Why ?
为什么?
Because a
and b
are unsigned, they can never be negative. 因为
a
和b
是无符号的,所以它们永远不会是负数。 The only way your assertions can fail is if one of them is 0. 断言失败的唯一方法是其中一个为0。
When you call your function with a signed int as a parameter, it will simply be converted to an unsigned it before the function executes (and thus before your asserts are checked). 当您使用signed int作为参数调用函数时,它将在函数执行之前简单地转换为unsigned(因此在检查断言之前)。 Converting a negative integer to an unsigned it will produce a positive integer because, as I said, there are no negative unsigned integers.
将负整数转换为无符号将产生正整数,因为正如我所说,没有负无符号整数。
You're not using a negative, it's converted to an unsigned int
because that's what the function takes as parameter. 你没有使用负数,它被转换为
unsigned int
因为这是函数作为参数所用的。
The assertions can only fail if the numbers are 0
. 断言只有在数字为
0
才会失败。
您的类型'unsigned int'将隐式-4转换为无符号等效
Because -4 interpreted as an unsigned (32 bit) int is 4294967291
, which is definitely positive. 因为-4解释为无符号(32位)int是
4294967291
,这肯定是正面的。
The following should work as you intend it to. 以下应该按照您的意愿工作。
unsigned int mulPositiveNumbers(int a, int b)
{
assert(a > 0); // Fail for (-4, 3)
assert(b > 0);
return (a*b);
}
While you are at it, you should also assert for whether the result of the multiplication will overflow, or choose a larger return type (eg long long ) 当你在它的时候,你也应该断言乘法的结果是否会溢出,或者选择一个更大的返回类型(例如long long )
尝试这个:
(unsigned int a ,unsigned int b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.