0
0
C++programming~20 mins

Reference declaration in C++ - Practice Problems & Coding Challenges

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

int main() {
    int x = 10;
    int &ref = x;
    ref = 20;
    std::cout << x << std::endl;
    return 0;
}
ACompilation error
B20
C10
DUndefined behavior
Attempts:
2 left
💡 Hint
Remember that a reference is an alias to the original variable.
Predict Output
intermediate
2:00remaining
Reference to const behavior
What will this program output?
C++
#include <iostream>

int main() {
    int x = 5;
    const int &ref = x;
    // ref = 10; // Uncommenting this line causes error
    std::cout << ref << std::endl;
    x = 15;
    std::cout << ref << std::endl;
    return 0;
}
A5\n5
BCompilation error
CUndefined behavior
D5\n15
Attempts:
2 left
💡 Hint
A const reference cannot be used to modify the variable, but the variable itself can change.
Predict Output
advanced
2:00remaining
Reference and pointer difference
What is the output of this code?
C++
#include <iostream>

int main() {
    int a = 7;
    int &ref = a;
    int *ptr = &a;
    ref = 10;
    *ptr = 20;
    std::cout << a << std::endl;
    return 0;
}
A7
BCompilation error
C20
D10
Attempts:
2 left
💡 Hint
Both reference and pointer modify the same variable 'a'.
Predict Output
advanced
2:00remaining
Reference initialization with temporary
What error or output does this code produce?
C++
#include <iostream>

int main() {
    int &ref = 5;
    std::cout << ref << std::endl;
    return 0;
}
ACompilation error
B5
CRuntime error
DUndefined behavior
Attempts:
2 left
💡 Hint
Non-const references cannot bind to temporary values.
🧠 Conceptual
expert
3:00remaining
Reference lifetime and dangling references
Consider this code snippet. What is the problem with it?
C++
#include <iostream>

int& getRef() {
    int x = 10;
    return x;
}

int main() {
    int &ref = getRef();
    std::cout << ref << std::endl;
    return 0;
}
AUndefined behavior due to dangling reference.
BIt prints 10 correctly.
CCompilation error due to returning reference to local variable.
DRuntime error due to null reference.
Attempts:
2 left
💡 Hint
Local variables die when the function ends, but the reference is returned.