Rewriting addition as a unary expression

Viewed 66

I came across the following statement:

A smart compiler can recognize that x = x + 1 can be treated the same as ++x.

Why is the prefix-operator used here instead of the post-fix operator (or either, if it doesn't matter)? For example, if I had the following loop:

while (x < 10) {
    ...
    x++; // wouldn't this be the same as doing ++x here?
}

What would be a case that shows how x = x + 1 is equivalent to ++x and not x++ ?

4 Answers

What would be a case that shows how x = x + 1 is equivalent to ++x and not x++ ?

Any case where the value of the expression is used.

One example: if((x = x + 1) < 10) is equivalent to if(++x < 10) but not if(x++ < 10).

Here's a simple example. Suppose you have something like this:

a = (x = x + 1);

This would be equivalent to

a = ++x;

but not to

a = x++;

It does not matter if you use ++i or i++ as a standalone expression. The only difference is the value of the expression, which is unused in both cases.

You could also write i += 1 or i = i + 1 and the compiler should generate the same code for all 4 variations (with optimisations enabled).

If the value of the expression is used, i = i + 1 and i += 1 are equivalent to ++i and all have the updated value, whereas i++ has the original value of i.

The expression i++ returns the value of i before incrementing it, while the expression ++i returns the value of i after incrementing.

For example:

int i = 1;
int j = i++; // j now equals 1, i equal 2

And ++i

int i = 1;
int j = ++i; // j and i both equal 2.

The expression x = x + 1 returns the value of x after incrementing, not before it, so it is equivalent to ++i

Related