0
#include<stdio.h>
void main() 
{
unsigned int i=65535;//assume that size of integer is 2 byte
printf("%d",i);
}

output=-1 //if size of integer is 2 byte

output=65535// if size of integer is 4 byte

can anyone explain me why it print -1 instead of 65535

according to me Size of interger is 2 byte i.e 16 bit . i=65535(Decimal value) Binary representation of 65535 is 1111111111111111. so it can accommodate 65535 easily

  • 2
    A **signed** 16bit integer normally has a range of -32768 to 32767 and binary 1111.... equals -1. [This post](http://stackoverflow.com/questions/1049722/what-is-2s-complement) provides many details abpout 2's complement – Ingo Leonhardt Sep 09 '14 at 13:26
  • What C implementation are you using, on what system? Is it an embedded system? (That's the only valid excuse for using `void main()`.) On modern systems, it's much more common for `int` to be 4 bytes. – Keith Thompson Sep 09 '14 at 14:24

1 Answers1

3

Use the "%u" conversion, rather than "%d". These are the conversion specifiers for unsigned (int) and signed (int) respectively.

Brett Hale
  • 21,653
  • 2
  • 61
  • 90
  • ya i agree with u brett .but i am curious to know this result with %d conversion –  Sep 09 '14 at 13:19
  • Size of interger is 2 byte i.e 16 bit . i=65535(Decimal value) Binary representation of 65535 is 1111111111111111 so it can easily accommodate 65535 and should be print 65535 –  Sep 09 '14 at 13:20
  • 1
    @anshumansingh - "%d" specifies that the argument is to be interpreted as a *signed* integer value. e.g., `-1` is `0xffff` in 2's complement representation. Values: `2^15 .. 2^16 - 1` yield: `-32768 .. -1` – Brett Hale Sep 09 '14 at 13:26