C++ recursion with a static accumulator and member mutation: what does this program print?
#include
class TestDrive
{
int x;
public:
TestDrive(int xx) { x = xx; }
int DriveIt(void);
};
int TestDrive::DriveIt(void)
{
static int value = 0; // accumulates across recursion
int m;
m = x % 2; // current parity bit
x = x / 2; // shift right by 1 (integer divide)
if ((x / 2)) DriveIt();
value = value + m * 10;
return value;
}
int main()
{
TestDrive TD(1234);
cout << TD.DriveIt() * 10 << endl;
return 0;
}
-
A300
-
B200
-
CGarbage value
-
D400
-
E100
Answer
Correct Answer: 400
Explanation
Introduction / Context: This program demonstrates recursion that peels bits off an integer while accumulating a result in a static local variable. Because the accumulator is static, its value persists across recursive calls and is updated during the unwind phase.
Given Data / Assumptions:
- Initial member x = 1234.
- At each call: m = x % 2; then x = x / 2.
- Recursive step occurs if (x / 2) is nonzero.
- After recursion, accumulator is updated: value = value + m * 10.
- Final output multiplies DriveIt() by 10.
Concept / Approach: Integer division by 2 shifts bits right. The test (x / 2) recurses as long as the result is nonzero, so the deepest frame corresponds to when x shrinks to 1 or 0. The update happens on unwinding—thus bits nearer the least significant positions contribute later. Multiplying by 10 at the end shifts the decimal-like accumulation one place to the left.
Step-by-Step Solution: Trace x: 1234→617 (m=0), 308 (0), 154 (0), 77 (1), 38 (0), 19 (1), 9 (1), 4 (0), 2 (0), 1 (0). On unwind, value adds m*10 in order: 0, +0, +10, +10, +0, +10, +0, +0, +10, +0 = 40. DriveIt() returns 40; printing multiplies by 10 → 400.
Verification / Alternative check: Run with a smaller number (e.g., 9) to see the same pattern: recursion depth follows division by 2, contributions occur after the recursive call.
Why Other Options Are Wrong: 200/300/100 result from miscounting the parity contributions; “Garbage value” is incorrect since control flow and returns are well-defined.
Common Pitfalls: Confusing when the accumulator is updated (after recursion), and overlooking that value is static.
Final Answer: 400