简体   繁体   中英

Can someone explain the output of following statement in C?

I am running the following code on my console but I am unable to understand this output?Why this program doesn't throw an error but instead print a value?

#include<stdio.h>
int main()
{
  unsigned int a = -1;
   printf("%u",a);
}

Output: 4294967295

I am unable to understand this output?

The signed int value -1 is converted to unsigned int . From C11 6.3.1.3p2 when converting a signed value to the "new type" which is unsigned int (you may find the cppreference implicit conversions page more approachable):

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

So -1 is not representable in unsigned int . So we should add or subtract UINT_MAX+1 to that value to get something that is representable in unsigned int . So we add UINT_MAX+1 to -1 , assuming on your platform UINT_MAX is 4294967295 , we get UINT_MAX + 1 - 1 = 4294967295 . Great, now the value is representable in unsigned int and that value is assigned.

Why this program doesn't throw an error

Because C is a weakly typed language in case of integer types and implicit conversions between some types are just part of the language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM