Which operator(s) in C have wrong precedence?

前端 未结 4 2098
面向向阳花
面向向阳花 2021-02-08 07:17

In the \"Introduction\" section of K&R C (2E) there is this paragraph:

C, like any other language, has its blemishes. Some of the operators h

4条回答
  •  遇见更好的自我
    2021-02-08 07:44

    It depends which precedence convention is considered "correct". There's no law of physics (or of the land) requiring precedence to be a certain way; it's evolved through practice over time.

    In mathematics, operator precedence is usually taken as "BODMAS" (Brackets, Order, Division, Multiplication, Addition, Subtraction). Brackets come first and Subtraction comes last.Ordering Mathematical Operations | BODMAS Order of operations

    Operator precedence in programming requires more rules as there are more operators, but you can distil out how it compares to BODMAS.

    The ANSI C precedence scheme is pictured here:

    As you can see, Unary Addition and Subtraction are at level 2 - ABOVE Multiplication and Division in level 3. This can be confusing to a mathematician on a superficial reading, as can precedence around suffix/postfix increment and decrement.

    To that extent, it is ALWAYS worth considering adding brackets in your mathematical code - even where syntactically unnecessary - to make sure to a HUMAN reader that your intention is clear. You lose nothing by doing it (although you might get flamed a bit by an uptight code reviewer, in which you can flame back about coding risk management). You might lose readability, but intention is always more important when debugging.

    And yes, the link you provide is a good example. Countless expensive production errors have resulted from this.

提交回复
热议问题