Does C always evalute all statements connected with && or ||
pretty simple question I have here, but I couldn't find the answer:
Assume I have some conditional clause made up of several conditions. E.g. something like
if((a == b && strcmp(string1, string)) || x <= 5)
My question is: Will all of those statements be evaluated, no matter what the result of the first ones was, or will the evaluation s开发者_C百科top once the result is clear.
As I am not sure whether my question is clear, here's an example:
if(a == 5 || b > 12 || (c = someFun()) == 3)
In this case, if a == 5, no further checks would be required, because the result of the big statement is TRUE, so we could simply continue. This would mean that someFun() would not be evaluated.
Is this the case? I know Java makes a difference here between && and & resp. || and | (the latter aren't available in C anyways), but I do not know how C handles this
These operators are short-circuiting in C (and C++).
C evaluates until it knows the answer, so:
EvalsToTrue() && EvalsToAnything() evaluates both
EvalsToFalse() && EvalsToAnything() evaluates only the first
EvalsToTrue() || EvalsToAnything() evaluates only the first
EvalsToFalse() || EvalsToAnything() evaluates both
The left-hand side expression is always evaluated. The right-hand side expression is evaluated as follows:
a || b
--b
will be evaluated only ifa
evaluates tofalse
a && b
--b
will be evaluated only ifa
evaluates totrue
&&
has higher precedence than ||
, thus
a || b && c
--b && c
will be evaluated only ifa
evaluates tofalse
a && b || c
--c
will be evaluated only ifa && b
evaluates tofalse
(a || b) && c
--c
will be evaluated only ifa || b
evaluates totrue
a && (b || c)
--b || c
will be evaluated only ifa
evaluates totrue
a && b && c
--c
will be evaluated only ifa && b
evaluate totrue
a || b || c
--c
will be evaluated only ifa || b
evaluate tofalse
Evaluation starts at left most.. and exits when the overall condition is no longer valid..
精彩评论