Question

While reading "C++ Primer Plus 5th edition", I saw this piece of code:

    cin.get(ch);
    ++ch;
    cout << ch;

So, this will lead to display the following character after ch. But, If I did it that way:

    cin.get(ch);
    cout << ch+1;

Now, cout will think ch is an int(try typecasting). So, why cout does so? And why if I added 1 to a char it will produce a number?. And why there's a difference between: ch++, and ch + 1.

Was it helpful?

Solution

The reason this occurs is the type of the literal 1 is int. When you add an int and a char you get an int, but when you increment a char, it remains a char.

Try this:

#include <iostream>

void print_type(char)
{
    std::cout << "char\n";
}
void print_type(int)
{
    std::cout << "int\n";
}
void print_type(long)
{
    std::cout << "long\n";
}

int main()
{
    char c = 1;
    int i = 1;
    long l = 1;

    print_type(c); // prints "char"
    print_type(i); // prints "int"
    print_type(l); // prints "long"

    print_type(c+i); // prints "int"
    print_type(l+i); // prints "long"
    print_type(c+l); // prints "long"

    print_type(c++); // prints "char"

    return 0;
}

OTHER TIPS

Please note - this is the answe to the original question, which has since been edited.

Now, cout will think ch is an int(try typecasting).

No it won't. It is not possible to change the type of a variable in C++.

++ch;

increments whatever is in ch.

ch + 1;

takes the value (contents) of ch, adds 1 to it and discards the result. Whatever is in ch is unchanged.

The statement ++ch; increments ch whereas ch + 1; doesn't.

Also, rememeber that '++ch' will do the increment before actually running the statement it is in, so that is why it remains a char.

int i = 0;
cout << ++i << endl;
cout << i++ << endl;
// both will print out 1.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top