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 modifying a variable passed by reference
What is the output of this C++ program?
C++
#include <iostream> void addFive(int &num) { num += 5; } int main() { int x = 10; addFive(x); std::cout << x << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that passing by reference allows the function to modify the original variable.
✗ Incorrect
The function addFive takes an int reference and adds 5 to it. Since x is passed by reference, its value changes from 10 to 15.
❓ Predict Output
intermediate2:00remaining
Effect of passing pointer vs reference
What will be printed by this program?
C++
#include <iostream> void increment(int *ptr) { (*ptr)++; } void incrementRef(int &ref) { ref++; } int main() { int a = 3; increment(&a); incrementRef(a); std::cout << a << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Both functions increase the value by one.
✗ Incorrect
First, increment increases a from 3 to 4 using a pointer. Then incrementRef increases it from 4 to 5 using a reference.
🔧 Debug
advanced2:00remaining
Identify the error with passing by reference
What error will this code produce?
C++
#include <iostream> void setToZero(int &num) { num = 0; } int main() { setToZero(5); return 0; }
Attempts:
2 left
💡 Hint
You cannot pass a literal to a non-const reference parameter.
✗ Incorrect
The function expects a reference to a variable, but 5 is a literal (rvalue). This causes a compilation error.
❓ Predict Output
advanced2:00remaining
Reference parameter with const qualifier
What is the output of this program?
C++
#include <iostream> void printValue(const int &num) { // num += 1; // Uncommenting this line causes error std::cout << num << std::endl; } int main() { int x = 7; printValue(x); return 0; }
Attempts:
2 left
💡 Hint
Const reference means the function cannot change the value.
✗ Incorrect
The function prints the value of x, which is 7. The commented line would cause a compilation error if uncommented.
❓ Predict Output
expert2:00remaining
Reference to pointer parameter behavior
What will be the output of this program?
C++
#include <iostream> void changePointer(int *&ptr) { static int y = 20; ptr = &y; } int main() { int x = 10; int *p = &x; changePointer(p); std::cout << *p << std::endl; return 0; }
Attempts:
2 left
💡 Hint
The function changes the pointer itself to point to a different variable.
✗ Incorrect
The function takes a reference to a pointer and changes it to point to y (20). So *p prints 20.