简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM