Question

Why I'm getting an error for:

int i=0;
++i++;

What does this error mean?

  unexpected type ++i++;                    
  required: variable  
  found:    value
Was it helpful?

Solution

It is about lvalue (left value). Lvalue is, what on the left side of an "=" stay can. Also, to what you can give a value. For example, you can't give a value to "4", but you can to give a value to "i". The expressions of variables aren't just so lvalues (with the exception of some very esoteric programming language).

If you write "++i++", it will be interpreted as (++i)++ or ++(i++). "i" is an lvalue, but "i++" or "++i" not, because they are expressions.

In C++, with some tricky operator overloading and reference-variable tricks, the C++ compiler could be tricked to handle this correctly.

OTHER TIPS

++i or i++ can be used on variable, but not on value so

i++
++i

is OK, but

2++
++2

is not.

Also result of ++i or i++ is not variable i but its original value (like when i=1, i++ would change i to 2 but would return 1). So even doing something like

(++i)++

would be incorrect because after ++i you would just try to use ++ on result of ++i which could be for example 2. This means you would try to perform 2++.

Similar problem exists in case of ++(i++)

Both prefix and suffix versions require the operation to be performed on a variable, not a value. You can increment a variable i with i++ or ++i but you can't increment 5 or 3.14.

++i++ means that you're trying to increment i by one and then increment the resulting value by one. There's the error.

Since ++ postfix and prefix have the same precedence, we need to resort to associativity to figure out what is going on.

The associativity of ++ is right to left.

That means that, conceptually, i++ happens first. But this, of course, is a fixed value (it's the value of i prior to incrementation). Therefore the prefix ++ is going to fail as it cannot operate on a fixed value.

++i++; is not valid. You can only do one at a time. ++ in prefix or ++ in postfix.
I see that you are trying to increment the value by two. You can do this as follows:

i++ // will post-increment the value of i
++i // will pre-increment the value of i  

i++ is the same as i = i + 1 or i += 1. Hence, you need some variable to which this value can be saved, as pointed out by Sotirios Delimanolis in the comments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top