0
0
C++programming~10 mins

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

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

Complete the code to declare a reference to an integer variable.

C++
int x = 10;
int& [1] = x;
Drag options to blanks, or click blank then click option'
Ar
Bptr
Cref
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using a pointer syntax instead of a reference.
Forgetting the ampersand (&) in the declaration.
2fill in blank
medium

Complete the code to modify the original variable through its reference.

C++
int a = 5;
int& ref = a;
ref [1] 10;
// Now a should be 10
Drag options to blanks, or click blank then click option'
A=
B+=
C-=
D*=
Attempts:
3 left
💡 Hint
Common Mistakes
Using an arithmetic operator instead of assignment.
Not understanding that the reference acts like the original variable.
3fill in blank
hard

Fix the error in the function parameter to accept a reference.

C++
void increment([1] num) {
    num++;
}

int main() {
    int x = 3;
    increment(x);
    // x should become 4
}
Drag options to blanks, or click blank then click option'
Aint
Bconst int&
Cint*
Dint&
Attempts:
3 left
💡 Hint
Common Mistakes
Passing by value, which does not modify the original variable.
Using a pointer without dereferencing inside the function.
4fill in blank
hard

Fill both blanks to create a function that swaps two integers using references.

C++
void swap([1]& x, [2]& y) {
    int temp = x;
    x = y;
    y = temp;
}
Drag options to blanks, or click blank then click option'
Avoid
Bint
Cconst
Dauto
Attempts:
3 left
💡 Hint
Common Mistakes
Using void& or const int& which prevents modification.
Using pointers instead of references.
5fill in blank
hard

Fill all three blanks to create a function that returns a reference to the larger of two integers.

C++
int& max([1]& a, [2]& b) {
    return (a [3] b) ? a : b;
}
Drag options to blanks, or click blank then click option'
Aconst
Bint
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using const int& which prevents returning a modifiable reference.
Using the wrong comparison operator.