Which operator(s) in C have wrong precedence?

前端 未结 4 2097
面向向阳花
面向向阳花 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

    There is a clear rule of precedence that is incontrovertible. The rule is so clear that for a strongly typed system (think Pascal) the wrong precedence would give clear unambiguous syntax errors at compile time. The problem with C is that since its type system is laissez faire the errors turn out to be more logical errors resulting in bugs rather than errors catch-able at compile time.

    The Rule

    Let ○ □ be two operators with type

    ○ : α × α → β
    □ : β × β → γ
    and α and γ are distinct types.

    Then

    x ○ y □ z can only mean (x ○ y) □ z, with type assignment
    x: α, y : α, z : β

    whereas x ○ (y □ z) would be a type error because ○ can only take an α whereas the right sub-expression can only produce a γ which is not α

    Now lets

    Apply this to C

    For the most part C gets it right

    (==) : number × number → boolean
    (&&) : boolean × boolean → boolean

    so && should be below == and it is so

    Likewise

    (+) : number × number → number
    (==) : number × number → boolean

    and so (+) must be above (==) which is once again correct

    However in the case of bitwise operators

    the &/| of two bit-patterns aka numbers produce a number ie
    (&), (|) : number × number → number
    (==) : number × number → boolean

    And so a typical mask query eg. x & 0x777 == 0x777
    can only make sense if (&) is treated as an arithmetic operator ie above (==)

    C puts it below which in light of the above type rules is wrong

    Of course Ive expressed the above in terms of math/type-inference

    In more pragmatic C terms x & 0x777 == 0x777 naturally groups as x & (0x777 == 0x777) (in the absence of explicit parenthesis)

    When can such a grouping have a legitimate use?
    I (personally) dont believe there is any

    IOW Dennis Ritchie's informal statement that these precedences are wrong can be given a more formal justification

提交回复
热议问题