开发者

Boolean AND and OR operations

开发者 https://www.devze.com 2023-04-04 12:51 出处:网络
Why does the following code output 1, inste开发者_JAVA技巧ad of 0? a || b should give me 1 and 1 && 0 is 0, right? I don\'t think logical operations evaluated from right to left.

Why does the following code output 1, inste开发者_JAVA技巧ad of 0? a || b should give me 1 and 1 && 0 is 0, right? I don't think logical operations evaluated from right to left.

int main()
{
    printf("%d\n", 1 || 1 && 0);
    return 0;
}


&& has higher precedence than ||. (Like how multiplication has higher precedence than addition.)


This is because of operator precedence. In C, the && operator has higher precedence than the || operator so it is evaluated first.


This comes from logical thinking development (boolean arithmetic), maybe even from hardware design using transistor-transistor-logic and lower level hardware languages (VHDL, for instance). We usually do two layer logics, first layer of AND's and second of OR's. The most typical situation being circuit minimization [1].

Typically, you combine input signals combinations as AND-ports inputs, and AND-ports outputs as OR-port inputs.

[1] http://en.wikipedia.org/wiki/Circuit_minimization

0

精彩评论

暂无评论...
验证码 换一张
取 消