tags:

views:

184

answers:

3

Hello. 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.

+8  A: 

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.

anon
What on earth gave me this idea?:D
Loai Najati
See my edit, thanks.
Loai Najati
-1 because you don't answer the question which was "why does c+1 gives an int?" which has a real answer. See answer from @itsadok
Vincent Robert
@Vincent The questioner has changed the question since I answered it - see the edit history.
anon
Yes, I did. Thanks Neil.
Loai Najati
+1  A: 

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

Uqqeli
+17  A: 

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;
}
itsadok
print_type(c+c); // prints "int"
Avram
@Avram: yep, binary arithmetic operators never operate on less than an int. It's fairly early on in the spec.
Steve Jessop
Thanks for that. It's really a good answer.
Loai Najati