schanti schul
schanti schul

Reputation: 721

issue with multiplying a define by a negative number

I want to understand the basics of this issue. I suspect that something is wrong with the casting, it is occasionally entering the if statement when it is not supposed to. i read some posts but couldn't understand what is the issue exactly. relevant code:

int32_t my_int_var;  // this should not be less than -20
#define MY_DEFAULT_VAR 20u
if(my_int_var < (-1*MY_DEFAULT_VAR)){
FailTest();
}

Upvotes: 0

Views: 69

Answers (1)

mksteve
mksteve

Reputation: 13085

Because of the 'u' at the end of MY_DEFAULT_VAR value, there is an implicit conversion from signed to unsigned by the expression

-1 * MY_DEFAULT_VAR

This results in an unsigned number so

the comparison is a large unsigned number 0xffffffe0

This now doesn't behave as expected e.g. if my_int_var was 20

if( 20 < 0xffffffe0 ) { /* this would now be true */

Upvotes: 4

Related Questions