Chris
Chris

Reputation: 2060

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

Upvotes: 3

Views: 252

Answers (4)

maheshgupta024
maheshgupta024

Reputation: 7877

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

Upvotes: 0

John Bode
John Bode

Reputation: 123578

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

Upvotes: 1

GlennS
GlennS

Reputation: 5611

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

Upvotes: 5

Mat
Mat

Reputation: 206859

These operators are short-circuiting in C (and C++).

Upvotes: 14

Related Questions