Challenge - 5 Problems
Reference Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of function modifying variable via reference
What is the output of this C++ code that uses a reference to modify a variable?
C++
#include <iostream> void addFive(int &num) { num += 5; } int main() { int a = 10; addFive(a); std::cout << a << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that passing by reference allows the function to change the original variable.
✗ Incorrect
The function addFive takes an int reference and adds 5 to it. Since 'a' is passed by reference, its value changes from 10 to 15.
🧠 Conceptual
intermediate1:30remaining
Why use references instead of pointers?
Which of the following is a key reason to use references instead of pointers in C++?
Attempts:
2 left
💡 Hint
Think about how references behave after initialization compared to pointers.
✗ Incorrect
References must be initialized when declared and cannot be changed to refer to another object, unlike pointers which can be reassigned and can be null.
❓ Predict Output
advanced2:00remaining
Output of swapping two variables using references
What is the output of this C++ code that swaps two integers using references?
C++
#include <iostream> void swap(int &x, int &y) { int temp = x; x = y; y = temp; } int main() { int a = 3, b = 7; swap(a, b); std::cout << a << " " << b << std::endl; return 0; }
Attempts:
2 left
💡 Hint
The swap function exchanges the values of the two variables passed by reference.
✗ Incorrect
The swap function uses references to directly change the values of 'a' and 'b'. After swapping, 'a' becomes 7 and 'b' becomes 3.
🔧 Debug
advanced2:00remaining
Identify the error in reference usage
What error does this C++ code produce and why?
C++
int& getReference() { int x = 10; return x; } int main() { int &ref = getReference(); return 0; }
Attempts:
2 left
💡 Hint
Think about the lifetime of the variable 'x' returned by reference.
✗ Incorrect
The function returns a reference to a local variable 'x' which is destroyed when the function ends, causing a dangling reference and undefined behavior at runtime.
🧠 Conceptual
expert2:30remaining
Why references improve function parameter passing
Which statement best explains why references are preferred for passing large objects to functions in C++?
Attempts:
2 left
💡 Hint
Consider the cost of copying large objects and the ability to modify them.
✗ Incorrect
Passing by reference avoids the overhead of copying large objects and allows the function to modify the original object if needed.