Reputation: 1517
Why the output of below mentioned program is 0
not 20
?
#include <stdio.h>
int main()
{
int i = 10, j = 0;
if (i || (j = i + 10))
/* do something */;
printf("%d\n",j);
}
Upvotes: 16
Views: 623
Reputation: 58271
Yes, the concept is called Short-Circuit (in logical &&
, ||
operators expression).
In the case of any logical expression (includes ||
, &&
) compiler stop evaluation expression as soon as result evaluated (and save executions).
The technique for short-circuit is:
!0 || any_expression
== 1
, so any_expression
not need to evaluate.
And because in your expression i
is not zero but its 10, so you can think if consdition (i || (j = i + 10))
just as i
.
Logical OR operator:
The||
operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand comparesunequal
to0
, the second operand isnot
evaluated.
Similarly for && (and operator):
0 && any_expression
== 0
, so any_expression
not need to evaluate.
In your expression:
(i || (j = i + 10) )
------------
^
| Could evaluate if i is 0,
as i = 10 (!0 = true), so j remains unchanged as second operand is not evaluated
For or ||
operator answer can be either 0, 1. To save execution, evaluation stops as soon as results find. So if first operand is non-zero result will be 1
(as above) for the expression. So for first operand i = 10
compares unequal to 0, the second operand (j = i + 10)
is not evaluated so j
remains 0
hence output of your code is 0
.
Note: Short-circuit behavior is not only in present in C but concept is common to many languages like Java, C++, Python. (but not all e.g. VB6).
In C short-circuiting of logical expressions is guaranteed has always been a feature of C. It was true when Dennis Ritchie designed and implemented the first version of C, still true in the 1989 C standard, and remains true in the C99 standard.
A related post: Is short-circuiting boolean operators mandated in C/C++? And evaluation order?
Upvotes: 27
Reputation: 85
because ||
is a short-circuit operator (so is the &&
operator).
so in (i || j = i+10)
, i
is 10, left part of ||
is true, the expression j = i+10
didn't happen, as a result, j=0
.
Upvotes: 3
Reputation: 2863
In if (i || (j = i + 10))
, there are two boolean expression to evaluate. The thing is, the first one is true, therefore there is no need to compute the second. It's purely ignored.
Upvotes: 5
Reputation: 212979
||
is a short-circuit operator - if the left hand side evaluates to true then the right hand side does not need to be evaluated. So, in your case, since i
is true then the expression j = i + 10
is not evaluated. If you set i
to 0 however then the right hand side will be evaluated,
Upvotes: 20