I am new in programming I have started learning with C. I wanted to learn about the precedence of the operators in the following
if ( p == 2 || p % 2 )
Please help me.
I am new in programming I have started learning with C. I wanted to learn about the precedence of the operators in the following
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.
Hence p == 2 will be executed first, followed by p % 2(because % has higher precedence than ||).
The result of these 2 will then be evaluated against ||.
Here
if ( p == 2 || p % 2 )
it looks like
if( operand1 || operand2)
where operand1 is p == 2 and operand2 is P % 2. Now the logical 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 is ==>
p == 2 (lets assume p is 2)
2 == 2 results in true hence operand2 doesn't get evaluated and if blocks looks like as
if(true) { }
Lets assume p is 3 then operand1 i.e 2 == 3 is false i.e operand2 gets evaluated i.e 3%2 i.e 1 that means if blocks looks like
if(true)
{
}
Let's assume p is 4 then operand1 i.e 2 == 4 is false i.e operand2 gets evaluated i.e 4%2 i.e 0 that means if blocks looks like
if(false)
{
}
Hope the above explanation makes sense to you.
About the associativity and precedence, please look into manual page of operator