简体   繁体   English

有人可以解释 C 中以下语句的 output 吗?

[英]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?我在控制台上运行以下代码,但我无法理解这个 output?为什么这个程序不抛出错误而是打印一个值?

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

Output: 4294967295 Output:4294967295

I am unable to understand this output?我无法理解这个 output?

The signed int value -1 is converted to unsigned int .signed int-1转换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):C11 6.3.1.3p2 开始,将有符号值转换为unsigned int的“新类型”(您可能会发现cppreference 隐式转换页面更容易接近):

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.当一个 integer 类型的值转换为除 _Bool 之外的另一个 integer 类型时,如果该值可以用新类型表示,则保持不变。

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 .所以-1unsigned int中是不可表示的。 So we should add or subtract UINT_MAX+1 to that value to get something that is representable in unsigned int .所以我们应该在该值上加上或减去UINT_MAX+1以获得可以用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 .所以我们将UINT_MAX+1添加到-1 ,假设在您的平台上UINT_MAX4294967295 ,我们得到UINT_MAX + 1 - 1 = 4294967295 Great, now the value is representable in unsigned int and that value is assigned.太好了,现在该值可以用unsigned int表示,并且该值已分配。

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.因为 C 是一种弱类型语言,在 integer 类型的情况下,某些类型之间的隐式转换只是语言的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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