简体   繁体   English

在c中使用宏

[英]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? 为什么会打印2? The SIZE is 8 which is greater than -1 so it should have printed 1. But why is it printing 2? SIZE是8,大于-1,因此应该打印1。但是为什么打印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). 您正在比较一个有符号的值( -1 )和一个无符号的值( SIZE生成的值是size_t ,它是无符号的)。

Thus -1 is promoted to an unsigned and becomes larger than SIZE . 因此-1提升为无符号,并变得大于SIZE

Take a look in type promotion in your favorite C book. 看一看您喜欢的C书中的类型提升。 The result of sizeof is unsigned, and then -1 gets transformed to unsigned, which is a big number. sizeof的结果是无符号的,然后将-1转换为无符号,这是一个很大的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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