6

Was wondering if the next statement could lead to a protection fault and other horrible stuff if value of next is NULL(node being a linked list).

if (!node->next || node->next->some_field != some_value) {

Im assuming the second part of the OR is not evaluated once the first part is true. Am I wrong in assuming this? Is this compiler specific?

Laz
  • 6,036
  • 10
  • 41
  • 54
  • 2
    You're not wrong. `if(ptr && ptr->foo == bar)` is safe, too. It's actually a code pattern used everyday by many programmers. – Agent_L Jan 10 '13 at 13:23
  • 4
    This is known as *"short-circuit evaluation"* should you need a term to search on. – Clifford Jan 10 '13 at 13:38
  • possible duplicate of [Little detail about using operator "or"](http://stackoverflow.com/questions/9131972/little-detail-about-using-operator-or) – Raymond Chen Jan 10 '13 at 15:42

5 Answers5

12

In the ISO-IEC-9899-1999 Standard (C99), Section 6.5.14:

The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int. 4 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.

This is not compiler-specific. If node->next is NULL, then the rest of the condition is never evaluated.

Raphael R.
  • 23,524
  • 1
  • 22
  • 18
  • 2
    This of course exists in C89/C90 too (section 6.3.14 (ISO numbering)) with the same text. In ISO/IEC 9899:2011 (C11), which replaces C99 as the current C standard, the wording is slightly different, but conveys the same information. – Chris Young Jan 10 '13 at 13:31
6

In an OR,

if ( expr_1 || expr_2)

expr_2 only gets 'tested' when expr_1 fails (is false)

In an AND

if( expr_1 && expr_2 )

expr_2 only gets 'tested' when expr_1 succeeds (is true)

John Furtado
  • 555
  • 2
  • 9
2

It is safe to assume that the right side boolean expression will not be evaluated if the left side evaluates to true. See relevant question.

Community
  • 1
  • 1
Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
2

It's not compiler specific. You can safely rely on short-circuiting and your code will work as expected.

P.P
  • 117,907
  • 20
  • 175
  • 238
2

You are correct.

It is compiler independent and always the first condition before OR operator(!node->next) is evaluated before evaluating the second condition(node->next->some_field != some_value) after OR operator. If the first condition is true, the entire expression just evaluates to true without evaluating the second condition.

You are just making the best use of this feature for your linked list. You are going further to access next pointer only if it is not NULL.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
sr01853
  • 6,043
  • 1
  • 19
  • 39