Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two unsigned char variables and result is int

Tags:

c++

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.

like image 555
scdmb Avatar asked Sep 24 '11 10:09

scdmb


People also ask

Can an unsigned char be an int?

unsigned char to integer assignment is no problem, but the other way around will have over flow problems at the high end.

Can you add unsigned char?

When adding two char or unsigned char variables, both are subject to integer promotions, which converts them to type int . In either case the sum is 140 and is of type int . This fits into unsigned char , so the resulting value of unsigned_sum is 140.

Can you add int to unsigned int C++?

When an unsigned int and an int are added together, the int is first converted to unsigned int before the addition takes place (and the result is also an unsigned int ).

What is the difference between unsigned and unsigned int?

There is no difference. unsigned and unsigned int are both synonyms for the same type (the unsigned version of the int type).


2 Answers

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.

like image 161
unwind Avatar answered Sep 27 '22 21:09

unwind


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.

like image 25
cpx Avatar answered Sep 27 '22 22:09

cpx