Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you increment/decrement a variable twice in the same expression?

When I try to compile this code

int main() {
    int i = 0;
    ++(++i);
}

I get this error message.

test.c:3:5: error: lvalue required as increment operand
     ++(++i);
     ^

What is the error message saying? Is this something that gets picked up by the parser, or is it only discovered during semantic analysis?

like image 545
northlane Avatar asked Jan 03 '23 14:01

northlane


2 Answers

++i will give an rvalue1 after the evaluation and you can't apply ++ on an rvalue.

§6.5.3.1 (p1):

The operand of the prefix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.


1. What is sometimes called "rvalue" is in this International Standard described as the "value of an expression". - §6.3.2.1 footnote 64).

like image 180
haccks Avatar answered Feb 13 '23 10:02

haccks


A lvalue is a value you can write to / assign to.

You can apply ++ to i (i is modified) but you cannot apply ++ to the result of the previous ++ operator. I wouldn't have any effect anyway.

Aside: C++ allows that (probably because ++ operator returns a non-const reference on the modified value)

like image 27
Jean-François Fabre Avatar answered Feb 13 '23 09:02

Jean-François Fabre