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

0

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.