1

I want to pass the sign changed version of some value to a function. I know how to check for overflow if the sign changes however I don't know about this one case.

int apple( int );

int a = 0;

apple( -a );

Is that defined behavior covered by the C/C++ standard? I'm passing -0 I would guess when a == 0. What about using something like this instead: a ? -a : a ? Thanks

4

3 回答 3

2

-a的情况下a == 0定义明确。标准要求的是它仍然为零。

它不保证值中的“位”不变(它们用于二进制补码,但不用于二进制补码,在这种情况下,无论其位模式如何,值都是“负零”)。if (!x)但是or的值应该为真if (x == 0),即使x它的值为“负零” - 由编译器和/或处理器制造商来确保它有效。

于 2013-09-16T21:51:06.553 回答
1

用值取反一个整数会0产生0. 无需任何特殊处理。

于 2013-09-16T21:48:41.273 回答
1

与数学一样,在 C++ 中-0 == 0

即使允许实现使用一个的补码(因此可以有 0 和 -0 的位模式),这不会改变值的含义,并且处理特定情况所需的任何额外计算-0将仅仅是实现细节,对你作为程序员来说是完全透明的。

于 2013-09-16T21:51:36.877 回答