在这种情况下负 0 会成为问题吗?
Would negative 0 be an issue in this situation?
我有一个简单的问题,是出于安全编码的考虑。
我遇到一个情况,我必须将除法余数或0
的负值赋给一个int
变量,所以我使用了以下表示法:
int a = -(b % c);
其中 b
和 c
都是正整数。表达式 (b % c)
将产生一个正数,或者 0
和 a
将被赋予结果的负值。
如果 (b % c)
产生 0
,-0
的计算结果是什么? 0
还是否定 0
?如果发生后者,会产生什么影响?
P.S我不知道负面0
是什么
-(b % c)
无法生成负数 0 因为 C 2018 6.2.6.2 3 说:
If the implementation supports negative zeros, they shall be generated only by:
— the &
, |
, ^
, ~
, <<
, and >>
operators with operands that produce such a value;
— the +
, -
, *
, /
, and %
operators where one operand is a negative zero and the result is zero;
— compound assignment operators based on the above cases.
即使我们将上面的解释包含 -
作为一元运算符,我们已经知道 b
和 c
是正整数,所以 b % c
不能产生负零,因此 -(b % c)
中 -
的操作数不是负零。
如果使用 ==
来比较负零和 non-negative 零,它会产生 true,因为 ==
基于操作数的值而不是它们的表示进行操作。
在现代 C 实现中,负零对于整数来说极为罕见。现代实现绝大多数使用没有负零的二进制补码。只有 specialized/historic/archaic 实现可以使用具有负零的替代整数表示(一个的补码和 sign-and-magnitude)。 Floating-point 表示通常有负零,但在比较值相等时它们等于正零(==
、!=
、<
、>
<=
和 >=
运算符)。
我有一个简单的问题,是出于安全编码的考虑。
我遇到一个情况,我必须将除法余数或0
的负值赋给一个int
变量,所以我使用了以下表示法:
int a = -(b % c);
其中 b
和 c
都是正整数。表达式 (b % c)
将产生一个正数,或者 0
和 a
将被赋予结果的负值。
如果 (b % c)
产生 0
,-0
的计算结果是什么? 0
还是否定 0
?如果发生后者,会产生什么影响?
P.S我不知道负面0
是什么
-(b % c)
无法生成负数 0 因为 C 2018 6.2.6.2 3 说:
If the implementation supports negative zeros, they shall be generated only by:
— the
&
,|
,^
,~
,<<
, and>>
operators with operands that produce such a value;— the
+
,-
,*
,/
, and%
operators where one operand is a negative zero and the result is zero;— compound assignment operators based on the above cases.
即使我们将上面的解释包含 -
作为一元运算符,我们已经知道 b
和 c
是正整数,所以 b % c
不能产生负零,因此 -(b % c)
中 -
的操作数不是负零。
如果使用 ==
来比较负零和 non-negative 零,它会产生 true,因为 ==
基于操作数的值而不是它们的表示进行操作。
在现代 C 实现中,负零对于整数来说极为罕见。现代实现绝大多数使用没有负零的二进制补码。只有 specialized/historic/archaic 实现可以使用具有负零的替代整数表示(一个的补码和 sign-and-magnitude)。 Floating-point 表示通常有负零,但在比较值相等时它们等于正零(==
、!=
、<
、>
<=
和 >=
运算符)。