Search code examples
cpointersoperator-precedencepost-increment

Operator precedence in the given expressions


Expression 1: *p++; where p is a pointer to integer.

p will be incremented first and then the value to which it is pointing to is taken due to associativity(right to left). Is it right?

Expression 2: a=*p++; where p is a pointer to integer.

Value of p is taken first and then assigned to a first then p is incremented due to post increment. Is it right?


Solution

  • First of all, let me tell you that, neither associativity nor order of evaluation is actually relevant here. It is all about the operator precedence. Let's see the definitions first. (emphasis mine)

    • Precedence : In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression.

    • Associativity: In programming languages, the associativity (or fixity) of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses.

    • Order of evaluation : Order of evaluation of the operands of any C operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified, except a few cases. There's mainly two types of evaluation: a) value computation b) side effect.


    Post-increment has higher precedence, so it will be evaluated first.

    Now, it so happens that the value increment is a side effect of the operation which is sequenced after the " value computation". So, the value computation result, will be the unchanged value of the operand p (which again, here, gets dereferenced due to use of * operator) and then, the increment takes place.

    Quoting C11, chapter §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 order of evaluation in both the cases are same, the only difference is, in the first case, the final value is discarded.

    If you use the first expression "as-is", your compiler should produce a warning about unused value.