Overflow and overflow C ++
Hi I'm new here, so please let me know if something is wrong and I will try to improve next time.
I am trying to understand how underflow and overflow works in C ++. We understand that if the range of variables is exceeded, it will start at the other end of the range. So if the minimum is short -32768, and if we do -1, then the new value should be SHRT_MAX. (32767) Here is my code:
#include<iostream.h>
#include<limits.h>
#include<conio.h>
int main ( void )
{
int testpositive =INT_MIN ;
short testnegative = SHRT_MIN ;
cout<< SHRT_MIN<<"\n";
cout << testnegative-1<<"\n";
cout << INT_MIN << "\n";
cout << testpositive-1 << "\n";
cout<<testpositive-2;
getch();
return 0;
}
source to share
The exact overflow / downgrade behavior is specified for types only unsigned
. For normal signed integer types, instead, the C ++ standard simply says anything can happen.
If we are talking about an x86 processor (or most other modern processors), indeed, the behavior is exactly what you describe, and for the CPU there is no difference between a signed or unsigned value (there are signed and unsigned operations, but the values themselves just bits).
Note that compilers may assume (and most modern optimizing compilers MUST indeed assume) that signed integer overflows cannot occur in a valid program, for example in code like the following:
int do_something();
int do_something_else();
void foo() {
int x = do_something();
int y = x + 1;
if (x < y) {
do_something();
} else {
do_something_else();
}
}
the compiler may skip the test and branch entirely else
in the generated code, because in a valid program the signed int is x
always less than x+1
(since signed overflow cannot be considered valid behavior) .If you replace int
with unsigned int
, however, the compiler has to generate code for the test, and for the else branch, since for unsigned types it is possible that x > x+1
.
For example, clang compiles code foo
in
foo(): # @foo()
push rax
call do_something()
pop rax
jmp do_something() # TAILCALL
where you can see that the ode just calls do_something
twice (except for the weird handling rax
) and there do_something_else
is really no mention of it. More or less the same code is generated gcc
.
source to share
Signed overflows are undefined behavior in C ++.
For example:
INT_MIN - 1
-INT_MIN
- expressions causing undefined behavior.
SHRT_MIN - 1
and is -SHRT_MIN
not undefined behavior in a 16-bit short
and 32-bit environment int
, because with integer shares, the operand is first promoted to int
. In a 16-bit environment short
, int
these expressions are undefined as well.
source to share