Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 200
JAN Avatar asked Dec 09 '22 21:12

JAN


2 Answers

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.

like image 136
sepp2k Avatar answered Dec 28 '22 14:12

sepp2k


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.

like image 40
Luchian Grigore Avatar answered Dec 28 '22 14:12

Luchian Grigore