用C unsigned int类型的行为负 [英] Unsigned int in C behaves negative

查看:122
本文介绍了用C unsigned int类型的行为负的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么一个unsigned int的输出为负以下code。
就像一个符号整数。

I don't understand why the output of an unsigned int is negative for the following code. Just like a signed int.

  uint32_t yyy=1<<31;
  printf("%d\n",yyy);

输出是:

-2147483648

-2147483648

这是 -2 ^ 31

推荐答案

格式说明了%d个预计的 INT ,而不是 unsigned int类型,所以code有不确定的行为。从C99标准部分的 7.19.6.1 fprintf函数的:

The format specifier for %d expects an int, not an unsigned int, so the code has undefined behaviour. From the C99 standard section 7.19.6.1 The fprintf function:

如果任何参数都不是正确的类型对应的转换规范,行为是不确定的。

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

使用%U unsigned int类型

uint32_t yyy=1u<<31;
printf("%u\n",yyy);

输出:


2147483648

这篇关于用C unsigned int类型的行为负的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆