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.
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