Home > Software design >  why are those comparisons giving me a different answer when they are mathematically the same in C?
why are those comparisons giving me a different answer when they are mathematically the same in C?

Time:11-14

char s[]="hello";
int i=5;
if(5>strlen(s)-i-1) printf("ok");
if(5>5-i-1) printf("ok2");

the output of the program above will be ok2 which is weird because the values of the conditions are the same and i can't figure out why it doesn't go inside the first if statement.

CodePudding user response:

You need to be aware of the rules for usual arithmetic conversions.

In an expression like a-b the operand with "smaller" type is converted to the type of the other operand.

Here "smaller" does not necessarily mean less bits but refers to a given order of types: unsigned types > signed types, long types > short types, floating point types > integer types.

In your cases you have int and size_t which normally is unsigned int (or unsigned long).

With this in your mind, your 2 conditions will look a bit different.

5 - i - 1 is of type int as each of the operands are of type int. The result is -1 and 5 > -1 is true.

In strlen(s) - i - 1 all operands will be converted to size_t which means the result is (size_t) -1 which evaluates to 2<<32-1 or 0xFFFFFFFF for 32 bit values. Now 5 > 0xFFFFFFFF is false.

This is why you get different results for your different conditions.

To get the same result you need to make 5 unsigned, too. That can be achieved by using 5u instead.

  • Related