Vaibhav Agarwal
Vaibhav Agarwal

Reputation: 1144

Different Outputs for a positive and negative value

Consider the code below:

#include<stdio.h>
int array[]={1,2,3,4,5,6,7,8};
#define SIZE (sizeof(array)/sizeof(int))

int main()
{
        printf("%d",SIZE);
        if(-1<=SIZE) printf("1");
        else printf("2");
        return 0;
}

I get 82 as output but if I replace if(-1<=SIZE) with if(0<=SIZE) or with if(1<=SIZE) means -1 in if clause with 0 or non negative number, then I get 81 as output. Why am I getting different outputs?

Upvotes: 3

Views: 464

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409336

The sizeof operator returns a size_t which is an unsigned integer type. When you convert -1 to an unsigned integer you get a very large number.

Turn on more warnings when building and the compiler will warn you about comparing signed and unsigned data types.

Upvotes: 10

Related Questions