using Macros in c
#include "stdafx.h"
#include<stdio.h>
int aarray[]={1,2,3,4,5,6,7,8};
#define SIZE (sizeof(aarray)/sizeof(int))
int main()
{
printf("%d\n",SIZE);
if(-1<=SIZE)printf("1\n");
else printf("2\n");
return 0;
}
Why does this prints 2? The SIZE is 8 which is greater than -1 so it should have printed 1. But why 开发者_JAVA技巧is it printing 2? Please help me understand.
You are comparing a signed value (-1
) and an unsigned value (the value produced by SIZE
is size_t
which is unsigned).
Thus -1
is promoted to an unsigned and becomes larger than SIZE
.
Take a look in type promotion in your favorite C book. The result of sizeof is unsigned, and then -1 gets transformed to unsigned, which is a big number.
精彩评论