0

Why does it print 2 when the value of SIZE is greater than -1?

Link to the code: http://ideone.com/VCdrKy

#include <stdio.h>
int array[] = {1,2,3,4,5,6,7,8};
#define SIZE (sizeof(array)/sizeof(int))

int main(void) {
    if(-1<=SIZE) printf("1");
    else printf("2");
    return 0;
}
Bipin
  • 1
  • 1
  • Never mix signed and unsigned. The result of `sizeof` is `size_t` which is an unsigned integer and `-1` is a signed integer. – DeiDei Aug 12 '17 at 09:33
  • Also: https://stackoverflow.com/questions/10165282/my-computer-thinks-that-signed-int-is-smaller-then-1, https://stackoverflow.com/questions/16981790/what-causes-the-array-in-the-following-code-not-to-be-printed. – Martin R Aug 12 '17 at 10:00

2 Answers2

1

Both arguments are in different type

Argument are 'converted' to 'common' type, and 'common' between signed -1 and unsigned SIZE is unsigned.

So -1 is converted -> 0xfffffff (depends on architecture) that is grater than SIZE

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22
1

From the C standard on integer conversions:

If the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Here -1 is of type int, and SIZE is of type size_t. On your c compiler, size_t is unsigned and has greater than or equal rank to int, so the -1 is converted to size_t, which gives a large positive number (SIZE_MAX)

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118