仅C ++:一元减0x80000000 [英] c++ only: unary minus for 0x80000000
问题描述
这个问题应该是给语言律师的.
This question is supposedly for language-lawyers.
假设有符号和无符号int均为32位宽.如n3337.pdf草案5.3.1.8中所述,
Suppose that signed and unsigned int are both 32 bits wide. As stated in the n3337.pdf draft, 5.3.1.8,
(-(0x80000000u)) = 0x100000000u-0x80000000u = 0x80000000u
但是我找不到问题的答案:签名 0x80000000将是一元减吗?是UB,定义的实现还是...?
But I can not find the answer to the question: what will be unary minus for signed 0x80000000? Is it UB, implementation defined, or ... ?
问题主要是关于运行时计算的.
说
signed int my_minus(signed int i) { return -i;}
....
int main() {
signed int a = -0x7FFFFFFF; // a looks like 0x80000001
signed int b = a - 1; // b looks like 0x80000000
std::cout << my_minus(b);
....
}
不过,欢迎您对其他2种情况发表评论:
Still, your comments on other 2 cases are welcome:
-
编译时常量折叠,例如
-(INT_MIN)
constexpr
的编译时计算(如果与编译时常量折叠不同).
Compile-time calculation of constexpr
(if there is a difference with compile-time constant folding).
(请查看 https://meta.stackexchange.com /questions/123713/is-splitting-a-question-a-好的做法,然后对重复进行投票.)
( Please look at https://meta.stackexchange.com/questions/123713/is-splitting-a-question-a-good-practice before voting for duplicate. )
推荐答案
带符号整数溢出始终是不确定的.在C ++规范部分的 5个表达式中,第4段:
Signed integer overflow is always undefined, as far as I know. From the C++ spec section 5 Expressions, paragraph 4:
如果在对表达式求值时,结果在数学上未定义或不在其类型的可表示值范围内,则行为不确定. [注意:大多数现有的C ++实现都忽略整数溢出.除以零的处理,使用零除数形成余数,并且所有浮点异常在机器之间都不同,并且通常可以通过库函数进行调整. -尾注]
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —endnote]
这篇关于仅C ++:一元减0x80000000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!