CPA-21-02 practice question 23 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; #define DEF_A 0 #define DEF_B DEF_A+1 #define DEF_C DEF_B+1 int main(int argc, char *argv[]) { cout

Full set: 257 questions
Answer options
A: It prints: 2 Correct answer
B: It prints: 10
C: It prints: 0
D: It prints: 1
Correct Answer:
A. It prints: 2
Explanation

Assuming standard preprocessor formatting (ignoring typographical line breaks in the prompt), the preprocessor performs textual substitution before compilation. DEFC is replaced by DEFB+1. Then, DEFB is replaced by DEFA+1, making the expression DEFA+1+1. Finally, DEFA is replaced by 0, resulting in the expression 0+1+1. The C++ compiler evaluates this constant arithmetic expression to 2. The cout object then prints the integer 2 to the standard output.

Why Incorrect

B: Incorrect because the arithmetic evaluates to 2, not 10. There is no string concatenation or base-2 conversion happening here. C: Incorrect because DEFC adds 2 to DEFA (which is 0), so the final evaluated result is not 0. D: Incorrect because DEFC adds 1 to DEFB, and DEFB adds 1 to DEFA, resulting in a total of 2, not 1.

References

1. ISO/IEC 14882:2014 (C++14 Standard), Section 16.3 "Macro replacement".

2. ISO/IEC 14882:2014 (C++14 Standard), Section 5.19 "Constant expressions".

3. MIT OpenCourseWare, 6.096 Introduction to C++, Lecture 2: The Preprocessor and Macros.

Scroll to Top