0
0
C++programming~20 mins

Passing parameters by reference 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 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;
}
A10
B15
C5
DCompilation error
Attempts:
2 left
💡 Hint
Remember that passing by reference allows the function to modify the original variable.
Predict Output
intermediate
2: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;
}
A3
B4
CCompilation error
D5
Attempts:
2 left
💡 Hint
Both functions increase the value by one.
🔧 Debug
advanced
2: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;
}
ACompilation error: cannot bind non-const lvalue reference to an rvalue
BRuntime error: segmentation fault
CNo error, program runs fine
DOutput: 0
Attempts:
2 left
💡 Hint
You cannot pass a literal to a non-const reference parameter.
Predict Output
advanced
2: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;
}
A7
B8
CCompilation error due to modification of const reference
DRuntime error
Attempts:
2 left
💡 Hint
Const reference means the function cannot change the value.
Predict Output
expert
2: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;
}
ACompilation error
B10
C20
DUndefined behavior
Attempts:
2 left
💡 Hint
The function changes the pointer itself to point to a different variable.