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

那年仲夏 提交于 2020-01-01 04:45:25

问题


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 ?


回答1:


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.




回答2:


I recommend this reading in every appropriate case. From Optimizing software in C++ -

Integer overflow is another security problem. The official C standard says that the behavior of signed integers in case of overflow is "undefined". This allows the compiler to ignore overflow or assume that it doesn't occur. In the case of the Gnu compiler, the assumption that signed integer overflow doesn't occur has the unfortunate consequence that it allows the compiler to optimize away an overflow check. There are a number of possible remedies against this problem: (1) check for overflow before it occurs, (2) use unsigned integers - they are guaranteed to wrap around, (3) trap integer overflow with the option -ftrapv, but this is extremely inefficient, (4) get a compiler warning for such optimizations with option -Wstrict-overflow=2, or (5) make the overflow behavior well-defined with option -fwrapv or -fno-strict-overflow.




回答3:


This is probably not what you want to do for two reasons:

  1. not every CPU has an overflow flag
  2. using C++ there is actually no way to access the overflow flag

the overflow checking tips that people have posted before might be useful.

if you really want to very write fast code that multiplies two integers and checks the overflow flag, you will have to use assembly. if you want some examples for x86, then do ask




回答4:


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.




回答5:


Yea it's possible. You'll have to use some asm.

inline bool isOverflow() {
_asm jo isOverflow_true
return false;
isOverflow_true:return true;
}

That's it.

EDIT: Apparently it wasn't clear that you need to use this after a calculation to see if the calculation overflows. Since you don't know what the compiler will do with your calculations it's recommend to do the calculation in asm too.



来源:https://stackoverflow.com/questions/14358943/is-it-possible-to-access-the-overflow-flag-register-in-a-cpu-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!