0
0
C++programming~10 mins

Passing parameters by reference in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a function parameter that passes an integer by reference.

C++
void increment([1] int &num) {
    num++;
}
Drag options to blanks, or click blank then click option'
Avolatile
Bconst
Csigned
Dunsigned
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the & symbol to pass by reference
Using pointer syntax instead of reference
2fill in blank
medium

Complete the code to call the function swap passing two integers by reference.

C++
void swap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 5, y = 10;
    swap([1], y);
    return 0;
}
Drag options to blanks, or click blank then click option'
Ax
B&x
C*x
Dint x
Attempts:
3 left
💡 Hint
Common Mistakes
Using &x in the function call, which is incorrect for references
Using *x which is for pointers
3fill in blank
hard

Fix the error in the function declaration to correctly pass a string by reference.

C++
#include <string>

void printName([1] std::string name) {
    std::cout << name << std::endl;
}
Drag options to blanks, or click blank then click option'
Aconst std::string &
Bstd::string *
Cstd::string &
Dstd::string
Attempts:
3 left
💡 Hint
Common Mistakes
Passing by value causes unnecessary copying
Using pointer syntax when reference is preferred
4fill in blank
hard

Fill both blanks to create a function that doubles an integer passed by reference and call it correctly.

C++
void doubleValue([1] int &num) {
    num *= 2;
}

int main() {
    int val = 7;
    doubleValue([2]);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aint
Bval
Cconst
D&val
Attempts:
3 left
💡 Hint
Common Mistakes
Using &val in the call which is incorrect for references
Adding const incorrectly in the parameter
5fill in blank
hard

Fill all three blanks to create a function that swaps two integers by reference and call it correctly.

C++
void swap([1] int &a, [2] int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 3, y = 4;
    swap([3], y);
    return 0;
}
Drag options to blanks, or click blank then click option'
Aint
Bconst
Cx
D&x
Attempts:
3 left
💡 Hint
Common Mistakes
Using const in parameters which prevents modification
Passing &x in the function call which is incorrect