1

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.

4

4 回答 4

18

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;
}
于 2009-08-02T11:11:59.520 回答
8

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.

于 2009-08-02T10:51:33.337 回答
1

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

于 2009-08-02T10:55:36.043 回答
0

另外,请记住,'++ch' 将在实际运行它所在的语句之前进行增量,所以这就是它仍然是 char 的原因。

int i = 0;
cout << ++i << endl;
cout << i++ << endl;
// both will print out 1.
于 2012-12-03T05:49:20.760 回答