否定INT_MIN是不确定的行为吗? [英] Is negating INT_MIN undefined behaviour?

查看:71
本文介绍了否定INT_MIN是不确定的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个变量 i 来自外部资源:

Let's say I have a variable i that comes from external sources:

int i = get_i();

假设 i INT_MIN 和二进制补码表示法, -i 是否未定义?

Assuming i is INT_MIN and two's complement representation, is -i undefined?

推荐答案

这取决于平台。 C支持负数的三种表示形式(请参见第6.2.6.2节 C99标准):

It depends on the platform. C supports three representations for negative numbers (see section 6.2.6.2 of the C99 standard):


  • 二进制补码。

  • 一个补码。

  • 符号和大小。

带补码,符号和大小, -INT_MIN定义了(等于 INT_MAX )。对于二进制补码,它取决于符号位为1且所有值位为零的值是陷阱表示还是常规值。如果它是正常值,则 -INT_MIN 溢出,导致未定义的行为(请参见 C99标准的第6.5 节)。如果是陷阱表示,则 -INT_MIN 等于 INT_MAX

With one's complement and sign and magnitude, -INT_MIN is defined (and equal to INT_MAX). With two's complement, it depends on whether the value with sign bit 1 and all value bits zero is a trap representation or a normal value. If it's a normal value, -INT_MIN overflows, resulting in undefined behavior (see section 6.5 of the C99 standard). If it's a trap representation, -INT_MIN equals INT_MAX.

也就是说,大多数现代平台使用的二进制补码没有陷阱表示,因此 -INT_MIN 通常会导致不确定的行为。

That said, most modern platforms use two's complement without trap representations, so -INT_MIN typically results in undefined behavior.

这篇关于否定INT_MIN是不确定的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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