2

Possible Duplicate:
Best way to detect integer overflow in C/C++

I have a plain C code which I compile using gcc version 4.4.3 on Ubuntu Linux.

In this code I have a variable of type unsigned long long int myvar. Now the code works such that I pass this variable myvar to a function myfunc() which computes a value for another variable which is also unsigned long long int, and that computed value is mathematically greater than the passed value, and this keeps on happening as the function myfunc() is called continuously until some break condition is met.

Now I want to make sure that whenever overflow happens (i.e. the computed value exceeds 9223372036854775807LL which is the LONG_MAX), I exit gracefully by displaying the message "Overflow detected" on the console.

  1. How Can I detect such overflow? Mostly I would like add any overflow detection code which is portable and does not rely on any standard library/plugin, but makes do with whatever OS available as a part of the language itself.

  2. If there is nothing, then Is there any internal variable set which I can use? or some other non-portable solution?

Any pointers would be useful.

Community
  • 1
  • 1
goldenmean
  • 18,376
  • 54
  • 154
  • 211
  • You cannot reliably detect overflow **after** it has occurred. You need to check if an operation **would** overflow and not do that operation. – pmg May 11 '11 at 11:39
  • @pmg - That's not entirely true. Many processors support an [overflow flag](http://en.wikipedia.org/wiki/Overflow_flag) that can be used to check whether or not the previous operation caused an overflow. Of course, checking it requires assembly code, and would not be portable cross-architecture. – aroth May 11 '11 at 11:44
  • This question was tagged C. In the C language, you cannot detect overflow after it has occurred. (Also note that in the C language, unsigned value wrapping is not considered "overflow" but a normal part of arithmetic.) – R.. GitHub STOP HELPING ICE May 11 '11 at 12:24

0 Answers0