How || and && works [duplicate]

柔情痞子 提交于 2021-02-05 06:59:57

问题


main( ) {
    int   i = 4, j = -1, k = 0, w, x, y, z ;
    w = i || j || k ;
    x = i && j && k ;
    y = i || j && k ;
    z = i && j || k ;
    printf ( "\nw = %d x = %d y = %d z = %d", w, x, y, z ) ;
}

I'm just learning C and I came across this code. I honestly dont know what w, x, y and z are assigned to. Apparently the output is as follows:

w = 1 x = 0 y = 1 z = 1

How is 'w' equal to 1? I dont get it.


回答1:


|| is the logical OR operator. From C11 s6.5.14 Logical OR operator

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

...the || operator guarantees left-to-right evaluation;

Applying this to the calculation for w we get

w = i || j || k  == (i || j) || k
                 == (non-zero || non-zero) || 0
                 == 1 || 0
                 == 1

Calculations for x, y, z are similar. C11 s6.5.13.3 states that the result from the && operator shall be 0 or 1.




回答2:


In C there is no "strong" built-in type for Boolean values, so integers are used instead. Results of evaluating logical expressions, such as ones using || and &&, can be assigned to integer variables.

When a value is used in a logical operator, the Boolean interpretation is very straightforward: zeros are interpreted as false, while all non-zero values are interpreted as true.

Now you should be able to figure out the expressions for yourself:

  • i || j || k evaluates as 1, because i and j are not zeros
  • i && j && k evaluates as 0, because k is zero,
  • ...and so on.



回答3:


This is how conceptually it works:

w = i || j || k;

w = 4 || -1 || 0; //values replaced

w = true || 0; //4 || -1 evaluates to true

w = (true); //true is being assigned to integer

w = 1; //0 is false, 1 is for true




回答4:


It is logical operations.

|| - means logical or, if at least one element is not 0, result is 1, otherwise its 0; && - means logical and, if all elements are 1, result is 1, otherwise its 0;

Logical and has higher priority, so:

x = 0 || 4 && 0;

Would be 0, because:

  1. 4&&0 = 0
  2. 0||0 = 0.

These operators are about full value of number. There are | and & operators connected with bits. Everything about working and priority is the same, just short example:

uint8_t x = 2 || 4 && 7;



1. 4=00000100 and 7=00000111
      00000100
   &  00000111
gives:00000100
 2. 2=00000010
      00000010
   |  00000100
gives:00000110, it is 6

I hope it is helpful.




回答5:


|| is the logical OR.

w = i || j || k;

is equivalent to:

w = (i != 0) || (j != 0) || (k != 0);

i is 4, which explains that w is true (which is evaluated to 1 as C uses integers to deal with booleans).

The same is applicable to && (the logical AND), etc.



来源:https://stackoverflow.com/questions/17348622/how-and-works

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