scdmb
scdmb

Reputation: 15611

Adding two unsigned char variables and result is int

There is code:

#include <iostream>
int main(){
  unsigned char a = 4, b = 255;
  int g = (unsigned char)a + (unsigned char)b;
  std::cout << g << std::endl;
  return 0;
}

Result:

259

Why the result is 259, not 3? If there are added two unsigned char variables, there should be overflow, result should be 3 and then it should convert from unsigned char 3 to int 3.

Upvotes: 12

Views: 11771

Answers (2)

cpx
cpx

Reputation: 17557

Integer arithmetic is never performed on data types smaller than int. For example, for types smaller than int e.g. if two types char and short int are added, they are promoted to int before any arithmetic operation and result is an integer type. If one of the types happened to be larger than int e.g long long int and int then int gets promoted to long long int and the result is long long int.

(§ 4.5/1) - An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.

Upvotes: 12

unwind
unwind

Reputation: 399733

The addition operation will first promote its operands to int, before doing the addition. This is how C works. If you want to truncate, you need to assign it back into a narrower type, such as unsigned char.

Upvotes: 16

Related Questions