Increment operators in programming

771 views

I’ve never been able to understand the difference between operators like x++ vs ++x. Please help explain these in a way my small brain can understand?

In: Technology

2 Answers

Anonymous 0 Comments

Even an operation that modifies data can be used itself as a fetched value itself. I can write `x = 5`, which sets a variable to the value of 5, but there is no requirement that his be a statement all by itself. In fact this statement is also usable as the number 5, inarguably since now both `x` and `5` have the same value. This can be useful to keep code smaller in certain conditions, such as in a loop where you want to both save something to memory but also check what its value is. You can do both at once. A common syntax might be:

while ((variable = GetSomeData()) != NULL) {
[…]

… could be written as the longer, but perhaps more clear:

while (True) {
variable = GetSomeData();
if (variable == NULL)
break;
[…]

… but it’s longer, and could be misleading that it’s meant to be an infinite loop. (C in particular includes a `for` loop which would be better suited here, but we’re ignoring that for the sake of the explanation)

`x++` has the action of `x=x+1`, except its own value is the value of `x` *BEFORE* the addition of 1.

`++x` is more literally `x=x+1` and hence has the value of `x` *AFTER* the addition of 1.

There are practical uses for both actions depending on what you’re up to.

Anonymous 0 Comments

x = 5
print(x) // 5
print(x++) // 5
print(x) // 6
print(++x) // 7
print(x) // 7

Both `x++` and `++x` increment x by 1, but `x++` evaluates to the old value of x, while `++x` evaluates to the new value of x.