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
  • 1
  • 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
  • 24,620
  • 4
  • 19
  • 40
user2736738
  • 30,126
  • 4
  • 38
  • 54