What is the importance of post increment and pre increment in C++?

156 views

What is the importance of post increment and pre increment in C++?

In: 7

7 Answers

Anonymous 0 Comments

Preincrement and post increment both do two different things in the same line of code: they increment a value and return a calue. The difference is the order in which they do these two things. Preincrementing (++x) increments x and returns the *new* value, while postincremebting (x++) returns the *old* value, then increments it.

As long as you use ++x or x++ on a line by themselves (including the “lines” between semicolons in a for-loop), the end result is more or less the same. Where they get weird is when you use them as part of other expressions. Consider “x = 1; y = x++ + 1;”. After this code, x and y would both equal 2, because the second line uses the old value. If the code were instead “x = 1; y = ++x + 1”, then x would equal 2 but y would equal 3, because you added to the new value.

Some people recommend against using these, because they can be fiddly and hard to understand. Technically, one can argue that C++’s own name is incorrect, because it implies you’re still using the old language evem though you would later go on to improve it. The name should be ++C, because you improved the language and then used your improvements.

You are viewing 1 out of 7 answers, click here to view all answers.