Challenge - 5 Problems
Reference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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; }
Attempts:
2 left
💡 Hint
Remember that a reference is an alias to the original variable.
✗ Incorrect
The reference 'ref' points to 'x'. Changing 'ref' changes 'x'. So output is 20.
❓ Predict Output
intermediate2: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; }
Attempts:
2 left
💡 Hint
A const reference cannot be used to modify the variable, but the variable itself can change.
✗ Incorrect
The const reference 'ref' refers to 'x'. When 'x' changes, 'ref' sees the new value.
❓ Predict Output
advanced2: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; }
Attempts:
2 left
💡 Hint
Both reference and pointer modify the same variable 'a'.
✗ Incorrect
First ref sets 'a' to 10, then pointer sets 'a' to 20. Final value is 20.
❓ Predict Output
advanced2: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; }
Attempts:
2 left
💡 Hint
Non-const references cannot bind to temporary values.
✗ Incorrect
Non-const references must bind to lvalues. '5' is an rvalue, so this is a compile error.
🧠 Conceptual
expert3: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; }
Attempts:
2 left
💡 Hint
Local variables die when the function ends, but the reference is returned.
✗ Incorrect
The function returns a reference to a local variable that no longer exists after the function ends, causing undefined behavior.