Angus
Angus

Reputation: 12621

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.

Upvotes: 1

Views: 84

Answers (2)

sidyll
sidyll

Reputation: 59277

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.

Upvotes: 2

cnicutar
cnicutar

Reputation: 182619

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.

Upvotes: 6

Related Questions