Are most compilers able to check if an addition operation that was performed earlier in the code resulted in a carry?
For example:
unsigned int n = 0xFFFFFFFF; // 8 F's
// doing some stuff here ...
n = n + 1;
// doing some stuff here, without changing the value of @var n
if (n >开发者_如何学JAVA; UINT_MAX) {
// n has a carry
}
Normally in C the way to tell if overflow occurred (at least with unsigned ints) is if the result of an addition is less than either of the operands. This would indicate an overflow. To the best of my knowledge there is no exception or notification of an overflow.
quick google search:
http://www.fefe.de/intof.html
Unfortunately, there is no way to access this carry bit from C directly.
Unsigned ints will wrap around to 0 in your example (assuming your c implementation uses 32 bit unsigned ints). The compiler can't tell if they wrap around, you need to check your result to see.
if (n > n + 1) { /* wrap around */ }
That is a runtime condition so is not in the domain of the compiler. In fact the CPU state of the carry operation will be lost with the next instruction that affects flags.
You need to detect such overflows in your program code.
精彩评论