0

According to the code below, size of int is not greater than -1. Why is it so? Why "False" was printed instead of "True"?

#include <stdio.h>
#include <stdlib.h>

int main() {

    if(sizeof(int) > -1) {
        printf("True\n");
    }
    else {
        printf("False\n");
    }

    // Here size of int is equals to 4
    printf("Size of int: %ld\n", sizeof(int));
    return 0;
}
Mohit Negi
  • 42
  • 2
  • 9

1 Answers1

3

Well sizeof returns size_t which is unsigned and when it is compared with int the int is promoted to unsigned and the bit representation all 1's now considered as unsigned, which is bigger than -1 and also that of sizeof int. That's why this result.

Correct format specifier for size_t is %zu.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Ah! I see, thanks for the explanation. – Mohit Negi Feb 22 '18 at 15:51
  • Is this actually a *promotion* or a *conversion*? – JFMR Feb 22 '18 at 15:52
  • @水飲み鳥.: Yes.... – user2736738 Feb 22 '18 at 15:53
  • What is standard saying about the rank of `size_t`? Because if it is lower than of the `int`, then the conversion will go the other way around, and it will eventually come `True`. – Eugene Sh. Feb 22 '18 at 16:04
  • @EugeneSh..: Ah yes that's what I am saying - AFAICR, unsigned higher rank than signed. – user2736738 Feb 22 '18 at 16:06
  • According to [this](https://stackoverflow.com/questions/40187755/adding-or-assigning-an-integer-literal-to-a-size-t) `size_t` *might* have a lower rank (well, that would be uncommon). – Eugene Sh. Feb 22 '18 at 16:10
  • @EugeneSh..: Ah yes the most usual case is what I have said in the comment but it's not the only one. You are right that if rank of int is lower o than rank of int (because of size) it will be **true**. – user2736738 Feb 22 '18 at 16:13
  • @EugeneSh.: Thanks for noting. C has these charms,. Let me know if you find anything interesting. – user2736738 Feb 22 '18 at 16:14