简体   繁体   English

C 运算符的优先级

[英]Precedence of C operators

I am new in programming I have started learning with C. I wanted to learn about the precedence of the operators in the following我是编程新手我已经开始学习 C。我想了解以下运算符的优先级

if ( p == 2 || p % 2 )

Please help me.请帮我。

Refer Precedence Of Operators and Short Circuiting .请参阅运算符短路的优先级

  • Precedence: Operator precedence determines how the operators and operands are grouped within an expression when there's more than one operator and they have different precedences.优先级:运算符优先级决定了当有多个运算符且它们具有不同的优先级时,运算符和操作数在表达式中的分组方式。

  • Associativity: Operator associativity is used when two operators of the same precedence appear in an expression.结合性:当两个优先级相同的运算符出现在表达式中时,使用运算符结合性。

Since ||因为|| exists, it is required that the left side of the ||存在,要求||的左边be evaluated first to decide if the right side of ||首先评估以决定||的右侧是否needs to be processed.需要处理。 If p == 2 returns true, p % 2 will not be evaluated.如果p == 2返回 true,则不会评估p % 2

Hence p == 2 will be executed first, followed by p % 2 (because % has higher precedence than || ).因此p == 2将首先执行,然后是p % 2 (因为%优先级高于|| )。

The result of these 2 will then be evaluated against ||然后将根据||评估这 2 个的结果. .

Here这里

if ( p == 2 || p % 2 )

it looks like看起来像

if( operand1 || operand2)

where operand1 is p == 2 and operand2 is P % 2 .其中操作operand1p == 2 ,操作operand2 p == 2P % 2 Now the logical OR ||现在逻辑 OR || truth table is真值表是

operand1  operand2  operand1 || operand2
0         0         0
0         1         1
1         0         1
1         1         1

From the above table, it's clear that if the first operand operand1 result is true then the result will always true & second operand operand2 doesn't get evaluated .从上表中可以清楚地看出,如果第一个操作数操作数operand1结果为真,那么结果将始终为真,第二个操作数操作数operand2不会被评估

operand1 is ==> operand1是 ==>

  • p == 2 (lets assume p is 2 ) p == 2 (假设p2

  • 2 == 2 results in true hence operand2 doesn't get evaluated and if blocks looks like as 2 == 2结果真实,因此operand2没有得到评估, if块的样子作为

    if(true) { }

Lets assume p is 3 then operand1 ie 2 == 3 is false ie operand2 gets evaluated ie 3%2 ie 1 that means if blocks looks like让我们假设p3然后操作operand12 == 3为假即操作operand2被评估即3%21这意味着if块看起来像

if(true)
{
}

Let's assume p is 4 then operand1 ie 2 == 4 is false ie operand2 gets evaluated ie 4%2 ie 0 that means if blocks looks like让我们假设p4然后操作operand12 == 4为假即操作operand2被评估即4%20这意味着if块看起来像

if(false)
{
}

Hope the above explanation makes sense to you.希望上面的解释对你有意义。

About the associativity and precedence, please look into manual page of operator关于结合性和优先级,请查看运算符的手册页

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM