I have tried some code in C
language but I have encountered this problem.
int i=0;
i=i+++ ++i; //works fine
//i=i++ +++i; gives error
My confusion is that how i+++
is running? but +++i
return error.
I have tried some code in C
language but I have encountered this problem.
int i=0;
i=i+++ ++i; //works fine
//i=i++ +++i; gives error
My confusion is that how i+++
is running? but +++i
return error.
C operators are parsed according to the “longest match” rule. Your first example is parsed as:
i = i ++ + ++ i ;
i = (i++) + (++i);
Whereas your second example is parsed as:
i = i ++ ++ + i ;
i = ((i++)++) + i;
The result of the post-increment operator is an rvalue, a copy of the previous value of the variable that was incremented. Applying another post-increment operator to an rvalue is an error because that operator requires an lvalue, intuitively, an expression such as i
or *p
that can be assigned to.
Also, this code contains undefined behaviour. You are reading i
and modifying it without an intervening sequence point—;
, &&
, ||
, ,
, or ?:
—which means that the program behaviour is unpredictable and will vary across compilers.
Both of those statements yield undefined behavior. However, the reason the first works fine is because your compiler interprets it as (i++)+ ++i;
, whereas the second line is i++ ++(+i)
, which makes no sense.