0

For example:

if(pos == -1 || character_array[pos] == 0) {

}

If pos is -1, can I count on this NEVER crashing?

Same goes with AND statements in which the first conditional fails.

ZPS
  • 1,566
  • 4
  • 16
  • 20
  • http://stackoverflow.com/questions/4613551/good-practice-in-c-lazy-evaluation – stijn Jul 27 '11 at 06:51
  • possible duplicate of [C : is there "lazy evaluation" when using && operator, as in C++ ?](http://stackoverflow.com/questions/3958864/c-is-there-lazy-evaluation-when-using-operator-as-in-c) – Jens Gustedt Jul 27 '11 at 07:38

3 Answers3

4

C supports short-circuit evaluation with the logical || and && operators, so in your case it should work as you describe, i.e. not crash.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
3

This is language specific, but most languages will ignore the rest of the statement if the first part is true for a ||.

Similarly, most languages will ignore the rest of the statement if a part of a && is false.

If you want everything to be executed, then use the single | and & operators instead.

2

Yes, you can count on this. The relevant parts of the C standard are 6.5.13:

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated.

and 6.5.14:

Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.

For example, the following is idiomatic C:

if (foo && foo->bar > 10)
caf
  • 233,326
  • 40
  • 323
  • 462