Short-circuit evaluation on C

Deadly 提交于 2019-11-26 11:38:14

问题


I\'m studying C from A Book on C by Kelley-Pohl, and there\'s this exercise that I don\'t understand:

int a = 0, b = 0, x;

x = 0 && (a = b = 777);
printf(\"%d %d %d\\n\", a, b, x);
x = 777 || (a = ++b);
printf(\"%d %d %d\\n\", a, b, x);

They just say to imagine the output and compare it to the real one. I thought the output would have been

777 777 0

778 778 1

but it is

0 0 0

0 0 1


回答1:


The && operator uses lazy evaluation. If either side of the && operator is false, then the whole expression is false.

C checks the truth value of the left hand side of the operator, which in your case is 0. Since 0 is false in c, then the right hand side expression of the operation, (a = b = 777), is never evaluated.

The second case is similar, except that || returns true if the left hand side expression returns true. Also remember that in c, anything that is not 0 is considered true.

Hope this helps.




回答2:


From the C Standard (6.5.13 Logical AND operator)

3 The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

and

4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

In this expression statement

x = 0 && (a = b = 777);

the first operand compares equal to 0. So the second operand is not evaluated that is the values of the variables a and b are not changed. So the variable x will be set to 0 according to the paragraph #3 of the section.

From the C Standard (6.5.14 Logical OR operator)

3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

and

4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

In this expression statement

x = 777 || (a = ++b);

the first operand compares unequal to 0. So the second operand is not evaluated that is the values of the variables a and b are not changed.. So the variable x will be set to 1 according to the paragraph #3 of the section.

If you will change the order of the operands in the expressions like

x = (a = b = 777) && 0;
x = (a = ++b) || 777;

you get the expected by you result.



来源:https://stackoverflow.com/questions/45848858/short-circuit-evaluation-on-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!