What is the result of the following expression ? (1 & 2) + (3 & 4)
2012
What is the result of the following expression ?
(1 & 2) + (3 & 4)Answer: D. 0 — ConceptThe bitwise AND operator & compares its two operands one bit position at a time. A bit of the result is 1 only when the corresponding bit is 1 in both…
- A.
1
- B.
3
- C.
2
- D.
0
Attempted by 154 students.
Show answer & explanation
Correct answer: D
Concept
The bitwise AND operator & compares its two operands one bit position at a time. A bit of the result is 1 only when the corresponding bit is 1 in both operands; in every other case that result bit is 0. It is a different operator from the logical AND &&, which tests the truthiness of whole values and yields only 0 or 1. In C the additive operator + binds more tightly than &, which is why each bitwise AND has to be parenthesised before its result can take part in an addition.
Application
Write the first operand pair in binary: 1 is 0001 and 2 is 0010.
Compare them column by column. 1 sets only the 20 column and 2 sets only the 21 column, so no column carries a 1 in both operands. The first parenthesis evaluates to 0000, that is 0.
Write the second operand pair in binary: 3 is 0011 and 4 is 0100.
Compare again. 3 sets the 20 and 21 columns while 4 sets only the 22 column, so once more no column carries a 1 in both operands. The second parenthesis evaluates to 0000, that is 0.
Add the two parenthesised results: 0 + 0 = 0. The expression evaluates to 0.
Cross-check
Substituting a different operator into the same skeleton shows how much the choice of operator matters:
Operator | 1 op 2 | 3 op 4 | Sum |
|---|---|---|---|
& (bitwise AND) | 0 | 0 | 0 |
&& (logical AND) | 1 | 1 | 2 |
| (bitwise OR) | 3 | 7 | 10 |
A useful sanity check on any bitwise AND: the result can never carry a bit that is missing from either operand, so for non-negative operands x & y can never exceed the smaller of x and y. Here every shared column is empty, so each parenthesis collapses all the way to zero.
The parentheses are also load-bearing. Written without them, 1 & 2 + 3 & 4 would be grouped as 1 & (2 + 3) & 4, because + has higher precedence than & in C.