difference b/w ch++ and ++ch




char ch;
cin.get(ch);


cout << ch++;

cout << ++ch;


please explain the two cout cases.

Put the code you need help with here.
[/code]
Last edited on
ch++ is using postfix operator, which will cause the value to be incremented by one after the call to cout << ch++; so this call will print the char.

++ch is using the prefix operator this means ch will be incremented before the call to cout << ++ch; completes. Since the postfix got executed after first cout, the second cout will print orginal value of char + 2

in other words
1
2
3
4
5
6
short a = 1;

short b = a++; //assign a to be and then increment the value of a
//here b will have value 1 and a will have value 2
short c = ++a; //increment value of a and then assign it to c
//Here c will have value 3 
The increment ++ is executed by precedence based on where it is. When it is placed after ch, the rest of the statement executes before its operation executes. Therefore the character you input will be printed to the console before being changed.

When you place the ++ before ch, its operation is moved to high precedence, and it is executed before ch is printed to the screen.

The code you gave will actually print out (when 'a' is inputted) "ac" instead of "ab" because when the value is given, it is printed to the screen and then incremented to 'b'. But on the second cout statement, the character is incremented once more (to 'c') before it is written out to the screen.

I hope this helps!
Last edited on
If you throw these in a quick program, you can see what the value of ch is before and after each step. I entered 'a' as the initial value of ch.

1
2
3
4
5
6
7
8
	char ch;
	cin.get(ch);

	cout << "After initial input: ch = " << ch << endl;
	cout << "Output of ch++ is " << ch++ << endl;
	cout << "Value of ch after ch++ is " << ch << endl;
	cout << "Output of ++ch is " << ++ch << endl;
	cout << "Value of ch after ++ch is " << ch << endl;
After initial input: ch = a
Output of ch++ is a
Value of ch after ch++ is b
Output of ++ch is c
Value of ch after ++ch is c


Both ch++ and ++ch increment the value of ch. The difference is in the value of the expression. The value of ch++ is the value of ch before it gets incremented. The value of ++ch is the value after it gets incremented.
thanks @codewalker @PrivateRyan @wildblue @dhayden
Topic archived. No new replies allowed.