Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I get an integer overflow when adding two chars? [duplicate]

Possible Duplicate:
Addition of two chars produces int

Given the following C++ code:

unsigned char a = 200;
unsigned char b = 100;

unsigned char c = (a + b) / 2;

The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)?

Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.

like image 297
deceleratedcaviar Avatar asked May 17 '11 00:05

deceleratedcaviar


People also ask

How do you know if an addition will overflow?

The rules for detecting overflow in a two's complement sum are simple: If the sum of two positive numbers yields a negative result, the sum has overflowed. If the sum of two negative numbers yields a positive result, the sum has overflowed. Otherwise, the sum has not overflowed.

How do you find integer overflow on addition?

Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.

How does integer overflow happen?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).


2 Answers

Neither C++ not C perform arithmetical computations withing "smaller" integer types like, char and short. These types almost always get promoted to int before any further computations begin. So, your expression is really evaluated as

unsigned char c = ((int) a + (int) b) / 2;

P.S. On some exotic platform where the range of int does not cover the range of unsigned char, the type unsigned int will be used as target type for promotion.

like image 177
AnT Avatar answered Oct 12 '22 14:10

AnT


No, this is not an error.

The compiler always calculates at minimum of integer precision, the result will be converted back to unsigned char on assignment only.

This is in the standard.

like image 39
sehe Avatar answered Oct 12 '22 15:10

sehe