Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access the overflow flag register in a CPU with C++?

After performing a mathematical operation, for say, multiplying two integers, is it possible to access the overflow flag register in a CPU with C++ ? If not what are other fast ways to check for an overflow ?

like image 467
Loers Antario Avatar asked Jan 16 '13 12:01

Loers Antario


People also ask

Does C detect overflow?

Detecting Overflow and Underflow in CIf both numbers are positive and the sum is negative, that means there is an overflow, so we return -1 else; if both numbers are negative and the sum is positive, that also means there is an overflow, so we return -1 else, no overflow.

What happens if there is overflow in C?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).

What is overflow flag register?

In computer processors, the overflow flag (sometimes called the V flag) is usually a single bit in a system status register used to indicate when an arithmetic overflow has occurred in an operation, indicating that the signed two's-complement result would not fit in the number of bits used for the result.


2 Answers

No, generally it's impossible. Some CPUs don't even have such a flag (e.g. MIPS).

The link provided in one of the comments will give you ideas on how you can do overflow checks.

Remember that in C and C++ signed integer overflows cause undefined behavior and legally you cannot perform overflow checks after the fact. You either need to use unsigned arithmetic or do the checks before arithmetic operations.

like image 180
Alexey Frunze Avatar answered Oct 29 '22 05:10

Alexey Frunze


You'd have to do the operation and check the overflow bit in inline assembly. You could do that and jump to a label on overflow, or (more generally but less efficiently) set a variable if it overflowed.

like image 42
Ted Percival Avatar answered Oct 29 '22 06:10

Ted Percival