Why are ++ and - only used before and after variables?

I'm reading "The C Programming Language" by Brian W. Kernighan and Dennis M. Ritchie, on page 46 says that "Increment and decrement operators can only be applied to variables, type expression is (i+j)++

illegal." Why can't it be used otherwise, just before or after variables?

+3


source to share


3 answers


I'm not sure what you mean by "just before variables". The ++

and operators --

(both postfix and prefix) require lvalues ​​to be modified as their operands. Lvalue is not necessarily represented by an immediate variable name.

For example you can do this

int a[10] = { 0 };
++*(a + 5);

      



Is *(a + 5)

"variable" in your understanding?

The problem with i + j

is not that it is "not a variable". The problem with it i + j

is that it is not an lvalue. This is why you cannot apply to it ++

.

In C, the term "variable" is sometimes used as a semi-informal synonym for "modifiable [scalar] object", which in turn is synonymous with modifiable lvalue [scalar]. The book you talked about could use the term "variable" in this semi-informal sense. In this sense, *(a + 5)

it is also a "variable".

+18


source


Can you do 8 ++?



The operand must be of the arithmetic or pointer data type and must reference a mutable data object.

+3


source


Because (i + j) is the result of adding two variables, you don't have a variable that actually stores i + j as just a computed result, so let's say i = 1 and j = 2, i + j equals 3 and 3 ++ is not valid since 3 is an r-value. For more information go here, http://eli.thegreenplace.net/2011/12/15/understanding-lvalues-and-rvalues-in-c-and-c

+2


source







All Articles