-3

why would the second line

int i=-3, j=2, k=0, m;
m = ++i && ++j || ++k;

terminate after ++j and ignore ++k ? I know the first half make TRUE value and would return TRUE whatever the following value is. But what is the condition to stop executing following instrument? As long as we can confirm the final value?

Joe
  • 46,419
  • 33
  • 155
  • 245
web rocker
  • 217
  • 1
  • 3
  • 10
  • 1
    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) – lorenzog Apr 07 '14 at 16:17
  • 1
    Duplicate of http://stackoverflow.com/questions/3958864/c-is-there-lazy-evaluation-when-using-operator-as-in-c; also, see http://c-faq.com/expr/shortcircuit.html for an explanation. – lorenzog Apr 07 '14 at 16:18
  • Just ask yourself: Why should it be evaluated at all? Maybe because the condition is met? – nietonfir Apr 07 '14 at 16:18
  • *Exact* duplicate of: [Why isn't "k" incremented in the statement "m = ++i && ++j || ++k" when "++i&&++j" evaluates to true?](http://stackoverflow.com/questions/16271779/why-isnt-k-incremented-in-the-statement-m-i-j-k-when-i) – Paul R Apr 07 '14 at 16:22

4 Answers4

1

The condition is exactly that. In an OR in C, whenever the result is found to be true, none of the rest of expressions are even evaluated.

If you want to test true or false and also be sure that the variables involved are increased, you should instead increase the variables before and then test:

++i;
++j;
++k;

m = i && j || k;
cnluzon
  • 1,054
  • 1
  • 11
  • 22
1

The || operator does not evaluate the second operand if the first operand evaluates TRUE. And the && operator does not evaluate the second operand if the first operand evaluates FALSE.

Sagar Jain
  • 7,475
  • 12
  • 47
  • 83
Fred
  • 8,582
  • 1
  • 21
  • 27
1

&& has higher precedence than that of ||. ++i and ++j binds to it and

m = ++i && ++j || ++k;  

is parsed as

m = (++i && ++j) || ++k;  

Since both the sub-expressions ++i and ++j are non zero, it is interpreted as true. Due to short circuit behavior of logical operators second (right) sub-expression is not evaluated in case of || if left becomes true.
Note that the left sub-expression for || is (++i && ++j), not j++.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

The operands of logical-AND and logical-OR expressions are evaluated from left to right. If the value of the first operand is sufficient to determine the result of the operation, the second operand is not evaluated. This is called "short-circuit evaluation." There is a sequence point after the first operand. See Sequence Points for more information.

Get the answer you want: here

haccks
  • 104,019
  • 25
  • 176
  • 264
Sagar Jain
  • 7,475
  • 12
  • 47
  • 83