0

Why in second printf when using %d I am not getting -1?

#include<stdio.h>
int main(){
    unsigned int u=-1;
    unsigned short int y=-1;
    printf("%d %u\n",u,u);
    printf("%d %u",y,y);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Sameer Raj
  • 35
  • 8

3 Answers3

2

Assuming int is 32-bit, short is 16-bit, and the architecture uses two's complement: When you set y=-1 the conversion from signed to unsigned yields 65535. When y is passed to printf it is promoted back to int, but this time the value 65535 is representable, thus printf will print 65535.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
2

The variable u is declared as having the type unsigned int.

unsigned int u=-1;

So you may not use the conversion specifier %d with this variable because the value of the u is not representable in an object of the type int. You have to use the conversion specifier %u.

As for your question then the variable y has the type unsigned short and its value as an unsigned value after the integer promotion to the type int can be represented in an object of the type int. So the positive value is outputted.

In this declaration

unsigned short int y=-1;

the integer constant -1 is converted to the type unsigned short and if your compiler supports the 2's complement representation of integers the converted value represents the positive value USHRT_MAX.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Because you have defined y as unsigned short. Because -1 is absolutely a signed int so the compiler will not store it into y as -1 instead it will be stored as 65535 which is the overflow result of -1. i.e. unsigned short range 65536 - 1.

Alaa Mahran
  • 663
  • 4
  • 12
  • The `unsigned short` range is not set in stone, but it's never `65536 - 1`. `[0, 65536)` (`[0, 65535]`) is possible.though – Ted Lyngmo Oct 28 '21 at 14:42
  • The `unsigned short` range is `[0, 65,535]` which means `65536` possibilities. so because -1 is stored in Two's complement in the memory it's stored like that `0b11111111` which will be interpreted as `65,535` when dealing with it as unsigned value. – Alaa Mahran Oct 28 '21 at 14:46
  • The `unsigned short` range _may_ be `[0,65535]`. It's _at least_ 16 bits but it can be wider. What I mainly opposed was "_unsigned short range `65536` `-` `1`_" which is a very strange way of describing ranges. – Ted Lyngmo Oct 28 '21 at 14:59