top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between a sequence point and operator precedence in C?

+1 vote
436 views
What is the difference between a sequence point and operator precedence in C?
posted Jun 27, 2017 by Archana Kumari

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

All operators produce a result. In addition, some operators, such as assignment operator = and compound assignment operators (+=, ++, >>=, etc.) produce side effects. The distinction between results and side effects is at the heart of this question.

Operator precedence governs the order in which operators are applied to produce their results. For instance, precedence rules require that * goes before +, + goes before &, and so on.

However, operator precedence says nothing about applying side effects. This is where sequence points (sequenced before, sequenced after, etc.) come into play. They say that in order for an expression to be well-defined, the application of side effects to the same location in memory must be separated by a sequence point.

This rule is broken by i = i++, because both ++ and = apply their side effects to the same variable i. First, ++ goes, because it has higher precedence. It computes its value by taking i's original value prior to the increment. Then = goes, because it has lower precedence. Its result is also the original value of i.

The crucial thing that is missing here is a sequence points separating side effects of the two operators. This is what makes behavior undefined.

answer Nov 9, 2017 by Manikandan J
...