1. ## Operator Precedence Puzzle

Hi

This is the code: Answer is below the code.
I tried to solve it my answer was wrong.

Code:
```int main()
{
int i = 0, j, k = 7, m = 5, n;

j = m +=2;

std::cout << j << std::endl;

j = k++ > 7;

std::cout << "j is: " << j << std::endl;
std::cout << "k is: " << k << std::endl;

j = i == 0 & k;

std::cout << j << std::endl;

n = !i >k >> 2;

std::cout << "n is: " << n << std::endl;

std::cout << "k is:" <<k << std::endl;

return 0;
}```

And its output:
Code:
```7
j is: 0
k is: 8
0
n is: 0
k is:8```
How does j = k++ > 7; produce 0 , I thought it must be 1 because k++ = 8 and is bigger than 7 and also
j = i == 0 & k; is equal to 0, I don't understand how it is equal to 0.

2. Originally Posted by sawer
Hi

This is the code: Answer is below the code.
I tried to solve it my answer was wrong.

Code:
```int main()
{
int i = 0, j, k = 7, m = 5, n;

j = m +=2;

std::cout << j << std::endl;

j = k++ > 7;

std::cout << "j is: " << j << std::endl;
std::cout << "k is: " << k << std::endl;

j = i == 0 & k;

std::cout << j << std::endl;

n = !i >k >> 2;

std::cout << "n is: " << n << std::endl;

std::cout << "k is:" <<k << std::endl;

return 0;
}```

And its output:
Code:
```7
j is: 0
k is: 8
0
n is: 0
k is:8```
How does j = k++ > 7; produce 0 , I thought it must be 1 because k++ = 8 and is bigger than 7 and also
j = i == 0 & k; is equal to 0, I don't understand how it is equal to 0.

K is 8 after k++, that is correct. However, that's exactly the difference between prefix and postfix increment. "++k" will increment k and use the new value in the rest of the statement, where "k++" will increment k and use the OLD value of k (7 in this case) in the rest of the statement. And as 7 is not greater than 7, it returns 0.

The second statement the trick is how to read the precedence. Is it:
Code:
`j = ((i == 0) & k)`
Or is it:

Code:
`j = (i == (0 & k))`

One of them sets j to 1, the other to 0. I'll leave it to you to find out which of the two is actually used. You can find out by thinking or look up the operator precedence rules.

Edit:
Technically, of course, it may have been interpreted as:

Code:
```(j = i == 0) & k
(j = i) == (0 & k)
((j = i) == 0) & k```
If I didn't forget any. But I'll tell you right now that assignment operators have very low precedence: the only operator with lower precedence less than that is the comma operator.
And I have to admit, I don't know the precedence rules. I just use paranthesis whenever I'm in doubt or when another programmer may be in doubt. In my opinion it enhances readability.

3. Originally Posted by sawer
because k++ = 8 and is bigger than 7
The result of the expression k++ is acatually 7, although the value of k immediately after it is 8. Think of it like this:
Code:
```int PostIncrement(int &x)
{
int y = x;
x = x + 1;
return y;
}

// ...

j = PostIncrement(k) > 7;```