Multiple logical operators in one line of code

倾然丶 夕夏残阳落幕 提交于 2019-12-13 10:52:41

问题


I was searching on Stack Overflow for the answer to this question but I haven't found an exact answer. I came up with this code. I know how operators are supposed to work but I don't understand them in this kind of problem. For example, in the first case, how can z and y still be 1 if there I am using ++y and ++z?

#include <stdio.h>

int main(void) {
    int x, y, z;

    x = y = z = 1;
    ++x || ++y && ++z;
    printf("x = %d y = %d z = %d\n", x, y, z);

    x = y = z = 1;
    ++x && ++y || ++z;
    printf("x = %d y = %d z = %d\n", x, y, z);

    x = y = z = 1;
    ++x && ++y && ++z;
    printf("x = %d y = %d z = %d\n", x, y, z);

    x = y = z = -1;
    ++x && ++y || ++z;
    printf("x = %d y = %d z = %d\n", x, y, z);

    x = y = z = -1;
    ++x || ++y && ++z;
    printf("x = %d y = %d z = %d\n", x, y, z);

    x = y = z = -1;
    ++x && ++y && ++z;
    printf("x = %d y = %d z = %d\n", x, y, z);

    return 0;
}

As results i get:

x = 2 y = 1 z = 1
x = 2 y = 2 z = 1
x = 2 y = 2 z = 2
x = 0 y = -1 z = 0
x = 0 y = 0 z = -1
x = 0 y = -1 z = -1

回答1:


This is a result of the evaluation of the logical expressions: as soon as it has been determined that an expression is false (or true), the remaining operators are not evaluated anymore. E.g.:

++x || ++y && ++z;

As x is one, the expression will be true independent of what z or y are, so ++y and ++z are not performed anymore.




回答2:


Due to precedence rules, the expression in the first example is identical to ( && has higher precedence than || ):

++x || ( ++y && ++z ) ;

So we're left with the operator || and its two operands ++x and ( ++y && ++z ). This operator is evaluated from left to right, so ++x is evaluated first. But this operator also short-circuits, which means that if the first operand evaluates to true, as in this case ++x does, the second operand ( ++y && ++z ) won't be evaluated.




回答3:


The reason is that you used || and &&.

&& and || operators short-circuit evaluations, that is, for && if the first operand evaluates to false, the second operand is never evaluated because the result would always be false. Similarly, for || if the result of the first operand is true, the second operand is never operated.

The single ampersand "&" can be said as "bit-wise AND" operator and The double ampersand "&&" can be mentioned as "Logical AND" operator.

for example, in this line: ++x || ++y && ++z; x is 1 so the boolean value of ++x is true. because you used || the statment "++y && ++z" is not run at all and the value of y and z is 1.

if you will use & and | the value will increase to 2.



来源:https://stackoverflow.com/questions/35382271/multiple-logical-operators-in-one-line-of-code

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