开发者

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 if a evaluates to false
  • a && b -- b will be evaluated only if a evaluates to true

&& has higher precedence than ||, thus

  • a || b && c -- b && c will be evaluated only if a evaluates to false
  • a && b || c -- c will be evaluated only if a && b evaluates to false
  • (a || b) && c -- c will be evaluated only if a || b evaluates to true
  • a && (b || c) -- b || c will be evaluated only if a evaluates to true
  • a && b && c -- c will be evaluated only if a && b evaluate to true
  • a || b || c -- c will be evaluated only if a || b evaluate to false


Evaluation starts at left most.. and exits when the overall condition is no longer valid..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜