Reputation: 153
I would like to change my char variable.
using namespace std;
int main()
{
char q;
q='b';
char c=127;
//cout << (int)q << endl<< static_cast<int>('z');
char d= static_cast<char>(static_cast<int>((static_cast<int>('z') +19)));
cout << (int)d << endl;
system("pause");
}
Intupt:
-115
Why after addition variable assigned -115?
Upvotes: 0
Views: 231
Reputation: 1
122 + 19 = 141 --> 1000 1101
binary
type char here might be 8 bits signed int,so the first bit '1' is its sign bit.
1000 1101
is what it's like in the computer memory.
But computers usually use ones-complement code to present negative number.
The true code of 1000 1101
is 1111 0011
,int the same way,the first '1' is its sign bit, so 1111 0011
is exactly -115
in 10base
Upvotes: 0
Reputation: 234705
On your platform, char
is an 8 bit signed
2's complement type. You are actually overflowing this type and the behaviour of overflowing a signed
integral type is undefined in C++. Don't do it.
Notes:
8 bit is mandated by the standard.
char
can be unsigned
or signed.
If unsigned
it must have the range [0, 255], and 255 + 1 will be 0. Overflow for an unsigned
type is defined.
If signed
it can either have the range -128 to +127 or -127 to +127. The latter range (1's complement) is not allowed from C++14. (Interestingly that's not a breaking change since a difference in moving from 1's to 2's complement would only be observable in a malformed program such as yours, if at all!)
A simple remedy? Use unsigned char
.
Upvotes: 1