Why does this if condition fail for comparison of negative and positive integers

manav m-n picture manav m-n · Aug 15, 2013 · Viewed 7.6k times · Source
#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?

Answer

Paul R picture Paul R · Aug 15, 2013

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.