整数转换(缩小,扩大),未定义的行为 [英] Integer conversions(narrowing, widening), undefined behaviour

查看:16
本文介绍了整数转换(缩小,扩大),未定义的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难以易于理解的方式找到有关此主题的信息,因此我要求对我发现的内容进行审查.这完全是关于转换和转换.

It was pretty difficult for me to find information on this subject in manner that I could easily understand, so I'm asking for a review of what I have found.It's all about conversion and conversion only.

在我将提到的示例中:

(signed/unsigned) int bigger;
(signed/unsigned) char smaller;

  1. 截断整数.(大->小)

  • 首先在MSB一侧截断 bigger以匹配smaller大小.
  • 其次,convert 截断结果为 signed/unsigned,具体取决于较小的类型.
  • first truncate bigger on MSB side to match smaller size.
  • second, convert truncated result to signed/unsigned depending on smaller type.


如果较大的值太大而无法放入较小的类型,则会导致未定义的行为(请纠正我).但是,我的规则应该适用于所有机器(也请纠正我)并且结果应该是可预测的.


If bigger value is too big to fit in smaller type, it results in undefined behaviour (correct me on that). However my rule should be working on all machines (correct me on that, too) and results should be predictable.

加宽整数(更小->更大)

a) signed char -> signed int

  • 在更小的前面加上 MSB(1 或 0)以匹配更大的尺寸
  • 转换为签名

b) signed char -> unsigned int

  • 在较小的前面加上 MSB(1 或 0)以匹配较大的大小.
  • 转换为无符号

c) unsigned char -> signed int

  • 添加 0 以匹配更大的尺寸
  • 转换为签名

d) unsigned char -> unsigned int

  • 添加 0 以匹配更大的尺寸
  • 转换为无符号

哪些未定义/未指定的行为可能会弹出?

Where are undefined/unspecified behaviours that I didn' mention that could pop up?

推荐答案

整数转换永远不会产生未定义的行为(它可以产生实现定义的行为).

An integral conversion never produces undefined behaviour (it can produce implementation-defined behaviour).

转换为可以表示正在转换的值的类型始终是明确定义的:值只是保持不变.

A conversion to a type that can represent the value being converted is always well-defined: the value simply stays unchanged.

到无符号类型的转换始终是明确定义的:该值取模 UINT_MAX+1(或目标类型允许的任何最大值).

A conversion to an unsigned type is always well-defined: the value is taken modulo UINT_MAX+1 (or whatever maximum value the target type admits).

转换为无法表示正在转换的值的有符号类型会导致实现定义的值或实现定义的信号.

A conversion to a signed type that cannot represent the value being converted results in either an implementation-defined value, or an implementation-defined signal.

请注意,上述规则是根据整数值定义的,而不是根据位序列定义的.

Note that the above rules are defined in terms of integer values and not in terms of sequences of bits.

这篇关于整数转换(缩小,扩大),未定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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