开发者

Why is the output not expected to be what it is?

Had been going through this code:

#include<cstdio>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {1,2,3,4,5,6,7};

int main()
{
    signed int d;
    printf("Total Elements in the array are => %d\n",TOTAL_ELEMENTS);
    for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
        开发者_开发知识库printf("%d\n",array[d+1]);
    return 0;
}

Now obviously it does not get into the for loop. Whats the reason?


The reason is that in C++ you're getting an implicit promotion. Even though d is declared as signed, when you compare it to (TOTAL_ELEMENTS-2) (which is unsigned due to sizeof), d gets promoted to unsigned. C++ has very specific rules which basically state that the unsigned value of d will then be the congruent unsigned value mod numeric_limits<unsigned>::max(). In this case, that comes out to the largest possible unsigned number which is clearly larger than the size of the array on the other side of the comparison.

Note that some compilers like g++ (with -Wall) can be told to warn about such comparisons so you can make sure that the code looks correct at compile time.


The program looks like it should throw a compile error. You're using "array" even before its definition. Switch the first two lines and it should be okay.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜