Home > Blockchain >  Conditional statement coming up as unsigned
Conditional statement coming up as unsigned

Time:12-14

#include <stdio.h>
#define Const_value sizeof(int)

int i = 100;
int j;
int main(){
    j = (Const_value - i > 0);
    printf("%ld, %d, %d",Const_value, i, j);
    return 0;
}

If I know that "Const_value" is 4 and "i" is 100 then the difference is -96. The expected outcome of j would be 0 in that case because -96 > 0 is a false statement and yet when this program is compiled and executed, j = 1. I assume it's because -96 is being treated as an unsigned value during the calculation but I fail to see any syntax that would indicate such a thing.

If I were to tweak the program into something like this:

#include <stdio.h>
#define Const_value sizeof(int)

int i = 100;
int j;
int main(){
    int x = Const_value - i;
    j = (x > 0);
    printf("%ld, %d, %d",Const_value, i, j);
    return 0;
}

Then I would get the expected result. What's the catch?

Outputs:

4, 100, 1
4, 100, 0

CodePudding user response:

Your Const_value macro evaluates to a size_t which is an unsigned value with rank equal to or higher than int. So, the result is unsigned.

Specifically, the result will be a size_t value. In other words, the i is implicitly promoted to size_t via the integer promotion rules, and then Const_value - i has unsigned overflow, wrapping the value around to a very large positive value. This then tests greater than zero.

  • Related