Search code examples
c++assertunsignedunsigned-integer

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 ?


Solution

  • 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.