c++ only: unary minus for 0x80000000

3

This question is supposedly for language-lawyers.

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

But I can not find the answer to the question: what will be unary minus for signed 0x80000000? Is it UB, implementation defined, or ... ?

The question is mostly about run-time calculation.

Say

   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);
       ....
   }

Still, your comments on other 2 cases are welcome:

  • Compile-time constant folding, say, -(INT_MIN)

  • Compile-time calculation of constexpr (if there is a difference with compile-time constant folding).


( Please look at https://meta.stackexchange.com/questions/123713/is-splitting-a-question-a-good-practice before voting for duplicate. )

c++
standards
language-lawyer
unary-operator
asked on Stack Overflow Feb 28, 2012 by user1123502 • edited Mar 20, 2017 by Community

2 Answers

4

Signed integer overflow is always undefined, as far as I know. From the C++ spec section 5 Expressions, paragraph 4:

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]

answered on Stack Overflow Feb 28, 2012 by Carl Norum
3

Signed integral types obey the rules of mathematical integers without added computer bullshit. So -std::numeric_limits< signed_type >::min() is going to be undefined behavior, if the given type cannot represent the resulting number.

In a constexpr, the implementation is required to reject that expression, as anything causing undefined behavior renders a constant expression invalid, as a diagnosable rule. In this case the rule is one of the forbidden items in §5.19,

— a result that is not mathematically defined or not in the range of representable values for its type;

In constant folding, the compiler is most likely to insert the overflowed value.

answered on Stack Overflow Feb 28, 2012 by Potatoswatter • edited Feb 28, 2012 by Potatoswatter

User contributions licensed under CC BY-SA 3.0