c - Does relational operator affect assignment operator operations? -


why output of below mentioned program 0 not 20 ?

#include <stdio.h>  int main() {     int = 10, j = 0;     if (i || (j = + 10))        /* */;                     printf("%d\n",j); } 

yes, concept called short-circuit (in logical &&, || operators expression).

in case of logical expression (includes ||, &&) compiler stop evaluation expression result evaluated (and save executions).

the technique short-circuit is:

!0 || any_expression == 1, any_expression not need evaluate.

and because in expression i not 0 10, can think if consdition (i || (j = + 10)) i.

logical or operator:
|| operator guarantees left-to-right evaluation; there sequence point after evaluation of first operand. if first operand compares unequal 0, second operand not evaluated.

similarly && (and operator):
0 && any_expression == 0, any_expression not need evaluate.

in expression:

(i || (j = + 10) )       ------------        ^        | evaluate if 0,         = 10 (!0 = true), j remains unchanged second operand not evaluated 

for or || operator answer can either 0, 1. save execution, evaluation stops results find. if first operand non-zero result 1 (as above) expression. first operand i = 10 compares unequal 0, second operand (j = + 10) not evaluated j remains 0 hence output of code 0.

note: short-circuit behavior not in present in c concept common many languages java, c++, python. (but not e.g. vb6).

in c short-circuiting of logical expressions guaranteed has been feature of c. true when dennis ritchie designed , implemented first version of c, still true in 1989 c standard, , remains true in c99 standard.

a related post: is short-circuiting boolean operators mandated in c/c++? , evaluation order?


Comments