Search code examples
cincrement

Why is the expression c=(a+b)++ not allowed in C?


I am trying to run a part of code and had to increment the value of a combined expression a+b. In trying to do this I wrote the statement

c=(a+b)++

Getting following error on this statement-
"expression must be a modifiable value"

Why am I getting this error and why is incrementing the value of an expression not allowed in C?


Solution

  • The postincrement operator can only be applied to an l-value, i.e. something that can appear to the left of the assignment operator, most commonly a variable.

    When x++ appears in an expression it is evaluated as x and x is increased afterward. For example a = 2; b = 2 * (a++); is equivalent to a = 2; b = 2 * a; a = a + 1;.

    Your example fails to compile because it is not possible to assign a value to a+b. To be more explicit c=(a+b)++ would be equivalent to c = (a + b); (a + b) = (a + b) + 1;, which makes no sense.