How to handle integer overflow when adding during health checks in a function?

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

I am writing a function in C, but the question is general. The function takes three integers and returns some information about these three integers.

Problem. I suspect that integers here may be at the maximum level, and this could cause an overflow.

For example: if I pass the maximum possible value, and b can be anything 1 - max, then in this case the expression (a + b)> c in, if the condition causes an overflow? If so, how can I handle this?

My solution was to store a long integer as a temporary variable in order to keep the value a + b and use it in the expression, but that sounds dirty.

Refer to this snippet:

int triangle_type(int a, int b, int c) { if (!((a+b)>c)&&((b+c) > a)&&((a+c>b))) { return -1; } } 
+4
source share
2 answers

There is no real signaling overflow for integers in current processors. Thus, on 32-bit processors, integer arithmetic is performed at a modular level of 2 ^ 32 at the bit level. When you add two int -s and an β€œoverflow” occurs, the overflow (or carry) bit is set to some state register (and the arithmetic operation is performed by the 2 ^ 32 module). If (as is usually the case) no machine instruction checks the overflow status bit, nothing happens.

Thus, the control flow will not change due to overflow (usually it will change when dividing by zero, for example, with the SIGEMT signal).

If you want to port an overflow case in C, you can check for example. that the sum of two positive int -s remains positive. (if it is negative, an overflow has occurred).

You may also be interested in bignums , for example. use the gmp library. You can also use <stdint.h> and gently use int32_t and int64_t with explicit clicks. Finally, you can (as most coders do), ignore this problem.

NB: As Jonathan remarked, you might get into undefined behavior or unspecified behavior . If you really care, use bonuses. However, you may not care at all.

+3
source

You can do something like this

 // returns true if a+b > c inline int safe_sum_greater (int a, int b, int c) { int a1 = a / 4; int a2 = a % 4; int b1 = b / 4; int b2 = b % 4; int c1 = c / 4; int c2 = c % 4; int s2 = a2 + b2; int s1 = a1 + b1 + s2 / 4; s2 = s2 % 4; return (s1 > c1) || ( (s1 == c1) && (s2 > c2) ); } 

Performance will not be bad, since only bit measures will be used. I did not think about it widely for negative numbers, so I use it with caution.

0
source

Source: https://habr.com/ru/post/1440919/


All Articles