1: #include <iostream>
2: using namespace std;
3: int main (void){
4: int i = 1, j = 2;
5: if (i > j && j > i) //if: i is bigger than j AND j is bigger than i ....
6: i++; //...then increment i by one. BUT this condition can never be true!
7:
8: if (i > j || j > i) //if: i is bigger than j OR j is bigger than i ....
9: j++; //...then increment j by one
10:
11: if (i | j) //if result of bitwise OR operation is true...
12: i++; //then increment i by one
13:
14: if (i & j) //if result of bitwise AND operation is true...
15: j++; //then increment j by one
16:
17: cout << i * j << endl;
18: return 0;
19: }
First if statement (line 5):
Pseudo-code: if(1 > 2 AND 2 > 1) -> false
This statement is always false so it can be ignored.
Second if statement (line 8):
Pseudo-code: if(1 > 2 OR 2 > 1) -> true
Either 1 > 2 or 2 > 1 has to be true. In this case 2 > 1 is true so it will incrementj
by one.
Integer j
is now 3 and i
is still at 1!
Third if statement (line 11):
Pseudo-code: if(1 | 3) -> true
This one is a bitwise OR operation:
The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1
In your case we have this scenario:
(binary) (decimal)
j: 0011 -> 3
i: 0001 -> 1
---------------------------- <== we are doing a bitwise OR operation here
0011 -> 3
So the result is a 3. Inside an if statement a three will be treated as true, so it will increment i
by one.
Integer i
is now 2 and j
is still at 3!
Fourth if statement (line 14):
Pseudo-code: if(2 & 3) -> false
This one is a bitwise AND operation:
The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
In your case we have this scenario:
(binary) (decimal)
i: 0010 -> 2
j: 0011 -> 3
---------------------------- <== we are doing a bitwise AND operation here
0010 -> 2
So the result is a 2. Inside an if statement a two will be treated as true, so it will increment j
by one.
Now we will end up with i
being 2 and j
being 4.
And when we multiply both integer variables we get 8 as the result!