Sizeof operator returns unsigned integer


The VC++ 6 compiler gives a warning when you try to use an unsafe mix of signed/unsigned value in a 'for' statement. Look at the following code snippet and try to determine its output

Code Snippet

    #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(x[0]))

    int main(void)
    {
        int array[] = {1, 2, 3, 4, 5};

        for(int n = -1; n < NUM_ELEMENTS(array) - 1; ++n)
            cout << array[n + 1] << endl;

        return 0;
    }

Output

The code does not output the elements of the array. It prints nothing.

Explanation

This is because the sizeof operator returns an unsigned integer. The variable 'n' in the for loop is a (signed) integer. According to compiler rules, a signed integer is promoted to unsigned when compared to an unsigned value. The value of -1 becomes unsigned 0xffffff. This is greater than the number of elements returned by the macro NUM_ELEMENTS. Therefore the control never enters the loop. To fix the problem, cast the output of NUM_ELEMENTS to an 'int'. The fixed 'for' loop becomes: 'for(int n = -1; n < (int) NUM_ELEMENTS(array) - 1; ++n)'.


http://www.geocities.com/sachinssharma
Hosted by www.Geocities.ws

1