Which operator(s) in C have wrong precedence?

前端 未结 4 2090
面向向阳花
面向向阳花 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 08:02

    Wrong may sound a bit too harsh. Normal people generally only care about the basic operators like +-*/^ and if those don't work like how they write in math, that may be called wrong. Fortunately those are "in order" in C (except power operator which doesn't exist)

    However there are some other operators that might not work as many people expect. For example the bitwise operators have lower precedence than comparison operators, which was already mentioned by Eric Postpischil. That's less convenient but still not quite "wrong" because there wasn't any defined standard for them before. They've just been invented in the last century during the advent of computers

    Another example is the shift operators << >> which have lower precedence than +-. Shifting is thought as multiplication and division, so people may expect that it should be at a higher level than +-. Writing x << a + b may make many people think that it's x*2a + b until they look at the precedence table. Besides (x << 2) + (x << 4) + (y << 6) is also less convenient than simple additions without parentheses


    In other languages there are many real examples of "wrong" precedence

    • One example is T-SQL where -100/-100*10 = 0
    • PHP with the wrong associativity of ternary operators
    • Excel with wrong precedence (lower than unary minus) and associativity (left-to-right instead of right-to-left) of ^:
      • According to Excel, 4^3^2 = (4^3)^2. Is this really the standard mathematical convention for the order of exponentiation?
      • Why does =-x^2+x for x=3 in Excel result in 12 instead of -6?
      • Why is it that Microsoft Excel says that 8^(-1^(-8^7))) = 8 instead of 1/8?

提交回复
热议问题