CPA-21-02 practice question 35 of 35

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

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

The variable x is initialized to the integer value 0. A pointer ptr is declared and assigned the memory address of x using the address-of operator (&). When the cout statement executes, it prints the value of x directly, followed by a space, and then the dereferenced value of ptr using the indirection operator (). Since ptr points to x, dereferencing it yields the value stored in x, which is 0. Therefore, the program successfully compiles and outputs "0 0".

Why Incorrect

- Option B: The indirection operator () is used on ptr, which retrieves the value stored at the address (0), not the memory address itself.
- Option C: The value 1 is never assigned, incremented, or calculated anywhere in this program.
- Option D: The value 2 is never assigned or calculated in this program.

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 8.3.1 [dcl.ptr], Pointers.

- ISO/IEC 14882:2017 (C++17 Standard), Section 8.5.1.1 [expr.unary.op], Unary operators (address-of and indirection).

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

Scroll to Top