C programming: Division in an if-statement

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;
}

3 answers

  • answered 2017-08-12 09:34 Jacek Cz

    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

  • answered 2017-08-12 09:36 Paul Hankin

    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)

  • answered 2017-08-12 09:42 Keine Lust

    From "Expert C Programming" (Deep C Secrets):

    Why, and what, is the bug?

    int array[] = { 23, 34, 12, 17, 204, 99, 16 };
    #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
    main()
    {
        int d= -1, x;
        /* ... */
        if (d <= TOTAL_ELEMENTS-2)
            x = array[d+1];
            /* ... */
    

    The defined variable TOTAL_ELEMENTS has type unsigned int (because the return type of sizeof is "unsigned"). The test is comparing a signed int with an unsigned int quantity. So d is promoted to unsigned int. Interpreting -1 as an unsigned int yields a big positive number, making the clause false. This bug occurs under ANSI C, and under K&R C if sizeof() had an unsigned return type in a given implementation. It can be fixed by putting an int cast immediately before the TOTAL_ELEMENTS :

    if (d <= (int) TOTAL_ELEMENTS - 2)