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);
}
It is an assignment operator. It is a relational or comparison operator. It is used for assigning the value to a variable. It is used for comparing two values.
Relational operators are the ones that are used to validate a relationship between the two operands as if they are equal, greater than, less than, etc. Assignment operators are used for assigning values to a variable. A most simple example of the assignment operator is “equal to”.
These relational operators always result in false or true. Equality ( == ) first compares the type of its operands. If the types are different, then the result is false.
Relational operators compare values and return either TRUE or FALSE. Logical operators perform logical operations on TRUE and FALSE. Values used with a logical operator are converted into booleans prior to being evaluated.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With