cppadvanced10 minutes

Predict the Output of Complex Pointer and Reference Manipulations in C++

Analyze the given C++ code involving multiple levels of pointers, references, and pre/post-increment operators. Predict the exact output after all manipulations, demonstrating deep understanding of pointer arithmetic, reference binding, and operator precedence.

Challenge prompt

Given the code below, predict the exact output printed to the console without running the program. Pay close attention to the order of operations and how pointers and references are manipulated throughout the code.

Guidance

  • Carefully track the values of variables, pointers, and references after each operation.
  • Recall the difference between pre-increment (++i) and post-increment (i++) when used in complex expressions.
  • Understand how references to pointers behave and how modifying one affects the other.

Hints

  • Draw a timeline or table showing the value changes step-by-step.
  • Remember that the expression *++ptr increments the pointer before dereferencing, while (*ptr)++ increments the pointed value after accessing it.

Starter code

#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int* ptr = arr;
    int*& refPtr = ptr;

    std::cout << *ptr << " ";      // 1
    std::cout << *ptr++ << " ";    // 1
    std::cout << *ptr << " ";      // 2

    std::cout << *++ptr << " ";    // 3
    std::cout << (*ptr)++ << " ";  // 3
    std::cout << *ptr << " ";      // 4 (what about the increment?)

    refPtr++;
    std::cout << *refPtr << " ";  // ?
    
    return 0;
}

Expected output

1 1 2 3 3 4 5

Core concepts

pointer arithmeticreference to pointerpre-increment vs post-incrementoperator precedence

Challenge a Friend

Send this duel to someone else and see if they can solve it.