0

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();
}
schanti schul
  • 681
  • 3
  • 14
  • 1
    `#define MY_DEFAULT_VAR` is empty so the preprocessor replaces every occurence of `MY_DEFAULT_VAR` with nothing. That results in a syntax error `(-1*)` – pbn Aug 14 '18 at 08:20
  • please see fixed snippet – schanti schul Aug 14 '18 at 08:21
  • 2
    `20u` mean unsigned, you are multiplying unsigned by `-1` which makes no sense – pbn Aug 14 '18 at 08:21
  • 2
    What do you mean by "failing"? Does it not compile, or crash, or produce strange values, or send LinkedIn invitations to spammers, or what? – molbdnilo Aug 14 '18 at 08:28
  • 1
    There is no casting in that code, so that can't possibly be a problem. – molbdnilo Aug 14 '18 at 08:30
  • Btw you my_int_var not initialized, so what you expect to compare? – Nick S Aug 14 '18 at 08:38
  • Make sure you understand the [C11 Standard - 6.3.1.1 Boolean, characters, and integers(p2) (Integer Promotion Rules)](http://port70.net/~nsz/c/c11/n1570.html#6.3.1.1p2) – David C. Rankin Aug 14 '18 at 09:00
  • SO post about the topic: [Implicit type promotion rules](https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules) – Lundin Aug 14 '18 at 09:06

1 Answers1

4

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 */
Camile
  • 124
  • 9
mksteve
  • 12,614
  • 3
  • 28
  • 50