问题
Is
--foo++;
a valid statement in C? (Will it compile/run) And is there any practical application for this?
Sorry for changing the question in an edit but I found something out.
According to my C++ compiler (Visual Studio 2010):
--++foo;
is a valid command but
foo--++;
is not. Is there any reason for this?
回答1:
No, it is not valid because the result of the increment / decrement operators is not a lvalue.
EDIT: the OP edited his question by adding two more examples . So here we go, for the same reason:
--++foo;
--foo++;
foo--++;
are all invalid expression statements because the result of increment / decrement operators is not a lvalue. A compiler could extend the language and accepts these expressions, but a strictly conforming program cannot contain any of these expressions.
回答2:
As this is a C expression it should follow some cascading evaluation steps to find out result.
your expressions are
--++foo;
ok lets evaluate this first step:-
++foo;
must be evaluated to proceed
it is some how pre increment so foo become foo+1 .
then assignment happen
that is this evaluate to foo=foo+1;
and value of foo return for assignment to a variable(if nothing present then ignored).
so now our expression is like below
--(++foo); evaluated to
--(a constant value);//result of foo+1
again the statement evaluated like
a constant value=constant_valu+1;//right part is ok but left part is not a variable
as left side of assignment operator is not a variablle and raise an error.
so now no valid operand for -- /decrement operator So lvalue required error
来源:https://stackoverflow.com/questions/11679258/can-you-have-a-incrementor-and-a-decrementor-on-the-same-variable-in-the-same-st