CPA-21-02 practice question 13 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; int main() { int x=2, *y; y = &x; cout

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

In the provided C++ code, the integer variable x is initialized to 2. The pointer variable y is assigned the memory address of x using the address-of operator (&x). When the expression y + x is evaluated, the indirection (dereference) operator is applied to y, which retrieves the value stored at the memory address it points to (the value of x, which is 2). The expression then evaluates to 2 + 2, resulting in 4. The cout statement prints this result to the standard output.

Why Incorrect

A: Incorrect because the mathematical addition of the dereferenced pointer (2) and the variable (2) equals 4, not 1. B: Incorrect because it represents only the value of x or y, failing to account for the addition of both values. D: Incorrect because the sum of 2 and 2 is 4, not 0.

References

1. ISO/IEC 14882:2017 (C++17 Standard), Section 8.3.1 [expr.unary.op], Paragraph 1 (Indirection operator).

2. MIT OpenCourseWare, 6.096 Introduction to C++, Lecture 5: Pointers and Memory.

Scroll to Top