OR and AND operation in C

后端 未结 2 1573
不思量自难忘°
不思量自难忘° 2021-01-05 14:14

I have a doubt in the program below.

int main()
{
    int i = -3,j = 2, k = 0,m;
    m = ++i || ++j && ++k;
    printf(\"%d %d %d %d\\n\", i, j, k, m         


        
2条回答
  •  我在风中等你
    2021-01-05 14:54

    You used a short circuit or. Since ++i evaluates to -2, which is not 0, it short circuits and doesn't evaluate the rest of the expression. As a result, neither j or k get incremented.

    Also note that the short circuit operators, || and &&, are left associative and that || is higher precedence than &&. As a result, the || gets evaluated first, and early outs if the left hand side evaluates to true, while && early outs if the left hand side evaluates to false.

    EDIT: Fixed a mistake with explaining the precedence.

提交回复
热议问题