Difficulty: Medium
Correct Answer: Incorrect — it fails when the result would overflow the type width
Explanation:
Introduction / Context:
Programmers often say “left shift by 1 multiplies by 2.” While this is commonly true, the always in the statement can be misleading. Understanding when the equivalence holds and when it breaks is crucial for writing correct, portable bit-level code in C/C++.
Given Data / Assumptions:
Concept / Approach:
For unsigned types, left shift by k mathematically corresponds to multiplication by 2^k modulo 2^N, where N is the bit width. If the mathematical product stays within the representable range (no high bits lost), the operations agree. However, when the product requires more than N bits, left shift discards the overflowing bits, effectively wrapping modulo 2^N. Saying “always equivalent” ignores this overflow/wrap aspect. In contrast, the phrase “multiply by 2” usually implies mathematical integer multiplication without wraparound.
Step-by-Step Solution:
Verification / Alternative check:
Use wider types (e.g., unsigned long long) to see when overflow occurs. If you need guaranteed mathematical multiplication, promote to a wider type before shifting or multiplying.
Why Other Options Are Wrong:
Common Pitfalls:
Assuming left shift is a safe substitute for multiplication in all cases; overlooking overflow and silent wrap behavior.
Final Answer:
Incorrect — it fails when the result would overflow the type width.
Discussion & Comments