Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does unary minus operator for **signed** positive integer causes overflow?

Tags:

c++

Usually, INT_MIN is -2 ^ n and INT_MAX is 2 ^ n - 1

Is it guaranteed, that if x is positive number of type int then expressoin -x didn't cause overflow?

like image 603
diralik Avatar asked Sep 07 '17 11:09

diralik


People also ask

How can you tell if a signed integer is overflow?

Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.

What is overflow in signed integer?

"Signed integer overflow" means that you tried to store a value that's outside the range of values that the type can represent, and the result of that operation is undefined (in this particular case, your program halts with an error).

How does division cause integer overflow?

Division. Division is between two operands of arithmetic type. Overflow can occur during two's complement signed integer division when the dividend is equal to the minimum (negative) value for the signed integer type and the divisor is equal to −1 . Division operations are also susceptible to divide-by-zero errors.

What is the significance of unary minus operator?

The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. The result is not an lvalue. For example, if quality has the value 100 , -quality has the value -100 .


1 Answers

It is implicitly guaranteed, since it is true for all the allowed forms of signedness:

(examples with 16 bit int)

  • One's complement, INT_MIN = -32767, INT_MAX = 32767
  • Two's complement, INT_MIN = -32768, INT_MAX = 32767
  • Sign & magnitude, INT_MIN = -32767, INT_MAX = 32767

No other forms are allowed. As we can see, abs(INT_MIN) >= abs(INT_MAX) for all the allowed forms.

As a side note, INT_MAX is not allowed to be smaller than 32767 and INT_MIN is not allowed to be smaller than -32767. This is guaranteed by the requirements for limits.h.

like image 85
Lundin Avatar answered Nov 15 '22 01:11

Lundin