Leg*_*end 10 c++ overflow integer-overflow underflow
是否有一般方法来检查给定数据类型(uint32,int等)的溢出或下溢?
我正在做这样的事情:
uint32 a,b,c;
... //initialize a,b,c
if(b < c) {
a -= (c - b)
}
Run Code Online (Sandbox Code Playgroud)
当我在一些迭代后打印时,它会显示一个很大的数字,如:4294963846.
Ste*_*n L 10
要检查算术中的上溢/下溢,请将结果与原始值进行比较.
uint32 a,b;
//assign values
uint32 result = a + b;
if (result < a) {
//Overflow
}
Run Code Online (Sandbox Code Playgroud)
具体来说,检查将是:
if (a > (c-b)) {
//Underflow
}
Run Code Online (Sandbox Code Playgroud)