tags:

views:

48

answers:

3

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 > UINT_MAX) {
  // n has a carry
}
+2  A: 

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.

Amardeep
Would the compiler store the result of the operation of `n = n + 1` in a hidden variable and use it later in the condition (just like the compiler does sometimes in C++, with other cases) ?
Dor
The machine instructions that make up `n = n + 1` will affect the CPU flags. The compiler will generate code that takes flags into account if the operation requires it (variable larger than register size, for example). Beyond that sequence point it won't.
Amardeep
OK, 10x, +1 to you too
Dor
+2  A: 

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 */ }
Ian Wetherbee
+4  A: 

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.

Scott M.