I wrote the following code, I do not understand why I get -61 when I cout<<int(c).
int main() {
char a= 'a';
char b= 'b';
char c= a+b;
cout<<int(a)<<" ";
cout<<int(b)<<" ";
cout<<int(a+b)<<" ";
cout<<int(c)<<" ";
return 0;
char type may be signed or unsigned. It is tuned by a compiler flag. Char type is signed by default in most compilers and consists of 8 bits, one bit is for sign and 7 bits are for a numeric values. Thus the signed char represents numeric values from -128 up till 127. Such set of values is a ring. Further increasing of 127 returns to -128.
Any types smaller than int are promoted to int before applying operators, thus a+b is int 195. If you assign 195 to a signed char, the signed value overflow happens, that is considered as the undefined behaviour, because signed values may be represented differently than above. In you case, 195 is over 127 on 68, since127+1 is -128, thus 127+68 127+1+67 is -128+67 is -61.
C++ does not have operator+(char,char)<\/code> .
Therefore when you add two
char<\/code> s the arguments are promoted to
int<\/code> s and result is
int<\/code> .
The
195 - 256<\/code> is value
-61<\/code> .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.