简体   繁体   中英

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. The only way your assertions can fail is if one of them is 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). 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.

The assertions can only fail if the numbers are 0 .

您的类型'unsigned int'将隐式-4转换为无符号等效

Because -4 interpreted as an unsigned (32 bit) int is 4294967291 , which is definitely positive.

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 )

尝试这个:

(unsigned int a ,unsigned int b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM