#include <stdio.h>
int arr[] = {1,2,3,4,5,6,7,8};
#define SIZE (sizeof(arr)/sizeof(int))
int main()
{
printf("SIZE = %d\n", SIZE);
if ((-1) < SIZE)
printf("less");
else
printf("more");
}
The output after compiling with gcc
is "more"
. Why the if
condition fails even when -1 < 8
?
The problem is in your comparison:
if ((-1) < SIZE)
sizeof
typically returns an unsigned long
, so SIZE
will be unsigned long
, whereas -1
is just an int
. The rules for promotion in C and related languages mean that -1 will be converted to size_t
before the comparison, so -1
will become a very large positive value (the maximum value of an unsigned long
).
One way to fix this is to change the comparison to:
if (-1 < (long long)SIZE)
although it's actually a pointless comparison, since an unsigned value will always be >= 0 by definition, and the compiler may well warn you about this.
As subsequently noted by @Nobilis, you should always enable compiler warnings and take notice of them: if you had compiled with e.g. gcc -Wall ...
the compiler would have warned you of your bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With