# C+ - incrementing value of integer x help understand?

So an integer x has been assigned to a value of 7. I have some code below and I understand that the prefix line adds 1 to 7, printing 8. I understand postfix adds 1 to 7, printing 8. But I don't understand why the 'next' line prints 9. Like it's just printing the value of x, there's no increment or any special function that alters the value of x in that line. I don't understand why simply printing the value of x gives 9 instead of 7, the original value of x? Can someone explain?

To play around, I printed the value of x a 2nd time and it once again gives 9. I don't understand why. If I had to guess, I would say it's because there are 2 increment operations which add 1 and 1 to the value of 7. But then I don't understand why the 2nd line 'postfix' gives 8 instead of 9. Shouldn't it be incrementing from the updated value of 8 from the first line instead of the original value of 7? cout << "prefix: " << ++x << endl; //8 cout << "postfix: " << x++ << endl; //8 cout << "next: " << x << endl; //9 cout << "next: " << x << endl; //9

Formatting code better:

cout << "prefix: " << ++x << endl; //8

cout << "postfix: " << x++ << endl; //8

cout << "next: " << x << endl; //9

cout << "next: " << x << endl; //9

### 5 Answers

- mark_pocLv 61 month agoFavorite Answer
Prefix increments the variable before anything is said and done. Postfix increments the variable after everything is said and done.

So if the value of the variable is 7, and you say, cout << x++; then the printout will still be 7 since postfix increments the variable AFTER everything is said and done, you know, like AFTER printing out it's value. Then the next time just plain x is printed it will show 8 from the postfix.

In other words, postfix prints out the current value of x and then, just before leaving and turning out the lights, x is bumped up one. Then the next time x is printed it will show 8.

- Login to reply the answers

- JazSincLv 71 month ago
Since you're confused, don't use autoincrement this way.

Always put it on a line by itself.

Make your code more readable. If you can't read it yourself, you also can't expect anyone else to read it.

- Login to reply the answers

- EddieJLv 71 month ago
First line adds 1 to 7 and prints that. Now x = 8.

Second line prints the x, which is 8, and then adds 1 to it. Now x is 9.

- Login to reply the answers

- How do you think about the answers? You can sign in to vote the answer.
- Anonymous1 month ago
Prefix performs the addition operation, stores the result in the variable, and returns the CURRENT result

Postfix performs the addition operation, stores the result in the variable, and returns the ORIGINAL value

- Login to reply the answers