Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of logical OR execution in C

Tags:

c

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?

like image 559
Laz Avatar asked Jan 10 '13 13:01

Laz


People also ask

What is the order of logical operations?

The order of precedence is: logical complements ( not ) are performed first, logical conjunctions ( and ) are performed next, and logical disjunctions ( or ) are performed at the end. Notice: You can always use parentheses to change the default precedence.

Is there order of operations in C?

C operators are listed in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

What is the precedence of logical operators in C?

Operator precedence determines which operation is performed first in an expression with more than one operators with different precedence. Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left.


3 Answers

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.

like image 190
Raphael R. Avatar answered Oct 02 '22 22:10

Raphael R.


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)

like image 28
John Furtado Avatar answered Oct 02 '22 22:10

John Furtado


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.

like image 45
Audrius Meškauskas Avatar answered Oct 02 '22 22:10

Audrius Meškauskas