Dor
Dor

Reputation: 7504

Check if a word-sized variable has a carry after arithmetic operation

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
}

Upvotes: 0

Views: 241

Answers (3)

Scott M.
Scott M.

Reputation: 7347

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.

Upvotes: 4

Ian Wetherbee
Ian Wetherbee

Reputation: 6109

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 */ }

Upvotes: 2

Amardeep AC9MF
Amardeep AC9MF

Reputation: 19054

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.

Upvotes: 2

Related Questions