C中的哪个运算符具有错误的优先级? [英] Which operator(s) in C have wrong precedence?

查看:90
本文介绍了C中的哪个运算符具有错误的优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在K& R C(2E)的简介" 部分中,有以下段落:

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

与其他语言一样,

C也有其缺陷.一些运算符的优先级有误; ...

C, like any other language, has its blemishes. Some of the operators have the wrong precedence; ...

这些是哪个运算符?他们的优先级有何错误?

Which operators are these? How are their precedence wrong?

是其中一种情况吗?

推荐答案

有一个明确的优先规则是无可争议的. 规则是如此明确,以至于对于强类型系统(认为是Pascal),错误的优先级将在编译时给出明确的语法错误. C的问题在于,由于其类型系统是自由放任的,因此错误被证明是更多的逻辑错误,导致错误而不是在编译时可捕获的错误.

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.

让○□成为两个类型的运算符

Let ○ □ be two operators with type

○:α×α→β
□:β×β→γ
和α和γ是不同的类型.

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

然后

x○y□z可以仅表示(x○y)□z,且具有类型分配
x:α,y:α,z:β

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

而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 α

现在让我们

在大多数情况下,C都能正确处理

For the most part C gets it right

(==):数字×数字→布尔值
(&&):布尔值×布尔值→布尔值

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

所以&&应该在==以下并且是

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

类似

(+):数字×数字→数字
(==):数字×数字→布尔值

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

,因此(+)必须高于(==),这再次正确

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

但是对于按位运算符

&/|的两个位模式(又称为数字)产生一个数字 即
(&),(|):数字×数字→数字
(==):数字×数字→布尔值

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

因此是典型的掩码查询,例如. x & 0x777 == 0x777
仅在将(&)视为算术运算符(即在(==)以上)的情况下才有意义

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

C鉴于上述类型规则,将其置于错误的下方

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

在更实用的C术语中,x & 0x777 == 0x777自然地分组为 x & (0x777 == 0x777)(在没有显式括号的情况下)

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 的非正式声明指出,这些优先顺序错误可以给予更正式的理由

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

这篇关于C中的哪个运算符具有错误的优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆