c - "if an int can hold all values of the original type then the value is converted to int , else to unsigned int"——什么意思?

标签 c int type-conversion expression unsigned-integer

上面一行是关于 C 中的隐式积分提升/转换,摘自 Mike Banahan 的书 Section 2.8.1.1 (Link) .这是确切的段落:

No arithmetic is done by C at a precision shorter than int, so these conversions are implied almost whenever you use one of the objects listed below in an expression. The conversion is defined as follows:

Whenever a short or a char (or a bitfield or enumeration type which we haven't met yet) has the integral promotions applied

  • if an int can hold all of the values of the original type then the value is converted to int
  • otherwise, the conversion will be to unsigned int

这是我对粗体部分的困惑。请清除这些:

  • “否则”部分不是多余的吗?鉴于 int 大于其中任何一个,难道不是所有 shortchar 类型都默认适合 int尺寸? short 不适合 int 并且需要 unsigned int 的问题怎么会出现?
  • “否则”部分如何有效——如果将负短整数隐式转换为无符号整数,它的值不会改变吗?

虽然我很想将其视为微不足道并继续前进,但我觉得得到一个适当的解释会更好。谢谢。

最佳答案

int 类型(根据 C 标准)不必大于 shortint 只能“不短”于 short。例如,它们都可以是 16 位。在这种情况下,unsigned short 值可能无法放入 int 中。

(C data types 上的维基百科页面很有启发性。)

关于c - "if an int can hold all values of the original type then the value is converted to int , else to unsigned int"——什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955316/

相关文章:

c - 返回语句后的序列点?

C++ Conway 的生命游戏 - Cygwin 段错误(核心已转储)

java - 用户输入的数字不相加

c# - 从 Json.NET 中的 JToken 隐式转换

c - 为什么增加 float 会产生与预期不同的结果?

c++ - 适用于 Windows 7 的简单 "javac"样式命令行 C/C++ 编译器

python - 如何使用 Python 正确解码 .wav

c - 在用 C 编写一个简单的程序时遇到问题,有什么建议吗?

c# - 在不编写包装器的情况下禁用 C# 中第三方类的隐式转换?

c# - TypeDescriptor.GetConverter(typeof(string)) 无法转换为我的自定义类型