Rahul Choudhary
Rahul Choudhary

Reputation: 309

Adding a positive number to a char unexpectedly decreases it's value

I was trying the Caesar Cipher problem and got stuck at a very beginner like looking bug, but I don't know why my code is behaving that way. I added an integer to a char and expect it to increase in value, but I get a negative number instead. Here is my code. Although I found a way around it, but why does this code behave this way?

#include <iostream>
using std::cout; using std::endl;

int main()
{
    char ch ='w';
    int temp;
    temp = int(ch) + 9;
    ch = temp;
    cout<<temp<<endl;
    cout<<(int)ch;
    return 0;
}

Output:

128
-128

Upvotes: 1

Views: 89

Answers (1)

rustyx
rustyx

Reputation: 85531

A signed char type can typically hold values from -128 to 127.

With a value 128 it overflows.

Upvotes: 5

Related Questions