0
0
C++programming~20 mins

Why references are needed in C++ - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Reference Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
A15
B10
C5
DCompilation error
Attempts:
2 left
💡 Hint
Remember that passing by reference allows the function to change the original variable.
🧠 Conceptual
intermediate
1:30remaining
Why use references instead of pointers?
Which of the following is a key reason to use references instead of pointers in C++?
AReferences can be null, pointers cannot
BReferences use more memory than pointers
CReferences require explicit dereferencing like pointers
DReferences must be initialized and cannot be reseated, pointers can be changed
Attempts:
2 left
💡 Hint
Think about how references behave after initialization compared to pointers.
Predict Output
advanced
2: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;
}
A3 7
B0 0
C7 3
DCompilation error
Attempts:
2 left
💡 Hint
The swap function exchanges the values of the two variables passed by reference.
🔧 Debug
advanced
2: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;
}
ACompilation error: missing return statement
BRuntime error: dangling reference to local variable
CNo error, code runs fine
DCompilation error: cannot bind non-const lvalue reference to a temporary
Attempts:
2 left
💡 Hint
Think about the lifetime of the variable 'x' returned by reference.
🧠 Conceptual
expert
2:30remaining
Why references improve function parameter passing
Which statement best explains why references are preferred for passing large objects to functions in C++?
AReferences avoid copying the object, improving performance and allowing modification
BReferences create a copy of the object, increasing safety
CReferences always make the object constant inside the function
DReferences require explicit dereferencing, making code clearer
Attempts:
2 left
💡 Hint
Consider the cost of copying large objects and the ability to modify them.