Reputation: 15611
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
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