Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuit behavior of logical expressions in C in this example

Tags:

c

PROGRAM

#include <stdio.h>

int main(void)
{
    int i, j, k;

    i = 1; j = 1; k = 1;

    printf("%d ", ++i || ++j && ++k);
    printf("%d %d %d", i, j, k);

  return 0;
}

OUTCOME

1 2 1 1

I was expecting 1 1 2 2. Why? Because the && has precedence over ||. So I followed these steps: 1) j added 1, so j now values 2... 2) k added 1, so k now values 2... 3) 2 && 2, evaluates to 1... 4) No need of further evaluation as the right operand of || is true, so the whole expression must be true because of short circuit behavior of logical expressions...

Why am I wrong?

like image 850
user3646717 Avatar asked Jan 26 '15 05:01

user3646717


People also ask

What is short circuiting in C++?

Short circuiting is a functionality that skips evaluating parts of a (if/while/...) condition when able. In case of a logical operation on two operands, the first operand is evaluated (to true or false) and if there is a verdict (i.e first operand is false when using &&, first operand is true when using ||) the second operand is not evaluated.

What is short-circuiting in compiler?

Short-circuiting is one of the optimization steps of the compiler, in this step unnecessary calculation is avoided during the evaluation of an expression. Expression is evaluated from left to right.

What are the logical operators supported by C language?

Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then − Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.

What is a logical expression in control statements?

Logical Expressions Logical expressions are a fundamental part of control statements, and programmers form them with combinations of two kinds of operators: It's not possible to understand or to effectively use control statements without a thorough understanding of logical expressions and the operators that form them.


1 Answers

Precedence affects only the grouping. && has a higher precedence than || means:

++i || ++j && ++k

is equivalent to:

++i || (++j && ++k)

But that doesn't mean ++j && ++k is evaluated first. It's still evaluated left to right, and according to the short circuit rule of ||, ++i is true, so ++j && ++k is never evaluated.

like image 189
Yu Hao Avatar answered Oct 03 '22 11:10

Yu Hao