1

When I say

int a = 0;
int b = 1; 
a = b++; // a=1 then b=2

Why so?

Assignment operator has lower precedence than increment and decrement. Then why does this happen?

If I say:

a = b+1; // a=2

In this case, + is performed first then value is assigned. Why does this not happen in the former?

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60

3 Answers3

1

This has nothing to do with operator precedence. The postfix ++ operator is simply specified to behave that way internally, C11 6.5.2.4:

The value computation of the result is sequenced before the side effect of updating the stored value of the operand.

Meaning that b++ is first evaluated to 1 and this value is used by the rest of the expression, and the ++ is guaranteed to happen after that.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

You're (partially) correct. The precedence of the assignment operator is indeed lower than the postfix operator. However, where you're incorrect is what the postfix operator means.

According to the C11 Specification, Sec. 6.5.2.4:

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The value computation of the result is sequenced before the side effect of updating the stored value of the operand.

The specification is very clear about the semantics of this operator. It resolves to the original value of the operand and as a later side-effect its value is increased.

If you're looking to increment the value of both a and b in your example, use the prefix operator which is guaranteed to increment the value before the assignment. However, remember, using both postfix and prefix operators on the same variable in a single expression is undefined behavior. Don't do that!

darnir
  • 4,870
  • 4
  • 32
  • 47
0

Precedence comes from the grammar of the language. It tells us how to interpret the statement and, in crude terms, you can think it of as an implied bracketing of the expression.

So precedence means a=b++ is treated as a=(b++) rather than (a=b)++. In this instance, the other bracketing is not useful, but in other cases different bracketings might be meaningful, e.g. a & (b ^ c) compared with (a & b) ^ c.

Note that precendence (and associativity) are independent from the order of evaluation at runtime as well as the meaning of the operators.

In your particular instance the ++ operator meaning is to give the value of the operand and then, as a post condition, increment that operand. So a is assigned the value of b and b is separately incremented.

borrible
  • 17,120
  • 7
  • 53
  • 75