0
0
C++programming~20 mins

Reference vs pointer in C++ - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Reference vs Pointer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of reference and pointer modification
What is the output of this C++ code?
C++
#include <iostream>

int main() {
    int x = 10;
    int &ref = x;
    int *ptr = &x;
    ref = 20;
    *ptr = 30;
    std::cout << x << std::endl;
    return 0;
}
A10
B20
CCompilation error
D30
Attempts:
2 left
💡 Hint
Remember that both reference and pointer can modify the original variable.
Predict Output
intermediate
2:00remaining
Pointer vs reference reassignment
What is the output of this C++ code?
C++
#include <iostream>

int main() {
    int a = 5, b = 10;
    int *ptr = &a;
    int &ref = a;
    ptr = &b;
    ref = b;
    std::cout << a << " " << b << std::endl;
    return 0;
}
A10 10
B5 5
C5 10
DCompilation error
Attempts:
2 left
💡 Hint
Remember that references cannot be reseated but pointers can.
🔧 Debug
advanced
2:00remaining
Identify the error in pointer and reference usage
Which option will cause a compilation error in this code snippet?
C++
int x = 5;
int &ref = x;
int *ptr = &x;

// Options below show different assignments:
Aptr = &ref;
Bint &newRef = ptr;
Cref = 10;
D*ptr = 20;
Attempts:
2 left
💡 Hint
Check if the types on both sides match for references.
🧠 Conceptual
advanced
2:00remaining
Difference in memory behavior of references and pointers
Which statement correctly describes the difference between references and pointers in C++?
APointers can be reseated to point to different objects, references cannot be reseated after initialization.
BReferences require explicit dereferencing to access the value, pointers do not.
CReferences can be null, pointers cannot.
DPointers are automatically dereferenced when used, references require the * operator.
Attempts:
2 left
💡 Hint
Think about whether you can change what a reference or pointer points to after creation.
Predict Output
expert
3:00remaining
Output of complex pointer and reference manipulation
What is the output of this C++ code?
C++
#include <iostream>

void func(int *&ptrRef, int &ref) {
    *ptrRef = ref + 5;
    ref = *ptrRef + 5;
    ptrRef = &ref;
}

int main() {
    int a = 1, b = 2;
    int *p = &a;
    func(p, b);
    std::cout << a << " " << b << " " << *p << std::endl;
    return 0;
}
A1 2 1
B7 7 7
C7 12 12
DCompilation error
Attempts:
2 left
💡 Hint
Track carefully how the pointer reference and reference parameters modify values and pointers.