We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hello to everyone.
When I have to calculate the average of two integer numbers, first i have to add them. Sometimes an overflow occurs. One technique maybe to compare the result to one of the numbers, if result is lower, an overflow is recognized.
Is this good style or better use Assembler?
"One technique maybe to compare the result to one of the numbers, if result is lower, an overflow is recognized."
Bad style for C.
According to the C Standard, integer overflow can invoke undefined behavior, regarding which, the Standard has a note:
"Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message)."
From the Standard's perspective, having monkeys fly out your nose would be allowed too.
It is commendable that you are trying to work through the issue of integer overflow. The problem is that your implementation can cause overflow. Once you have caused an overflow, you have undefined behavior. If you want to deal with the issue of integer overflow in a rigorous way, you can't expect to detect it after the fact, you must avoid overflow before causing undefined behavior. This typically involves using wider types as has been suggested, or checking whether one operand is less than the integer distance between the other operand and INT_MAX (or INT_MIN), or converting to unsigned arithmetic and examining the result.
I'd suggest searching Google Groups' Usenet archive for "avoiding integer overflow". This will bring up some relevant comp.lang.c(.moderated) discussions amongst folks smarter than I and give you a better idea what I'm talking about.
the KISS solution avarage = (a/2) + (b/2);
Erik
But the KISS solution yields:
"average of 5 and 7 = 5"
which is not the best integer answer. It all depends on the accuracy that is needed. That said, if being off by one bit every now and then is okay, then it is certainly the fastest solution.
Steph-
The slightly less simple solution fixes that:
average = (a/2) + (b/2) + (a%2 + b%2) / 2;