Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR and AND operation in C

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);
    return 0;
}

I get the output as -2 2 0 1.

In OR operation if 1st value is true then it won't evaluate the 2nd one so i = -2 and j =2. Then comes the AND operation . It will check for both the value to be true.So if k = 1 then m = 1. So the output should be -2 2 1 1. I run and check and got output as -2 2 0 1 but I could not understand how.

like image 612
Angus Avatar asked Jun 25 '11 06:06

Angus


2 Answers

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.

like image 84
Mikola Avatar answered Nov 10 '22 01:11

Mikola


Nothing after the || is evaluated, since the result of the expression ++i is nonzero.

like image 26
Michael Foukarakis Avatar answered Nov 10 '22 01:11

Michael Foukarakis