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);
}
2

3 Answers 3

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.

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

Comments

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.

Comments

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.

3 Comments

The unsigned short range is not set in stone, but it's never 65536 - 1. [0, 65536) ([0, 65535]) is possible.though
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.
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.

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.