Assert that unsigned int a indeed positive doesn't work ?
-
29-06-2021 - |
Question
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.
OTHER TIPS
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
.
Your type 'unsigned int' converts implicitly -4 to unsigned equivalent
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 (e.g. long long)
Try this:
(unsigned int a ,unsigned int b)