0
0
C++programming~10 mins

Reference lifetime 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 create a reference to an integer variable.

C++
int x = 10;
int& ref = [1];
Drag options to blanks, or click blank then click option'
A10
Bx
C&x
D*x
Attempts:
3 left
💡 Hint
Common Mistakes
Using the value 10 instead of the variable name.
Using pointer syntax like &x or *x.
2fill in blank
medium

Complete the function to return a reference to the first element of the array.

C++
int& firstElement(int arr[]) {
    return [1];
}
Drag options to blanks, or click blank then click option'
Aarr[0]
B*arr
Carr
D&arr[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the array name instead of an element.
Returning a pointer instead of a reference.
3fill in blank
hard

Fill in the blank with the variable name that matches the return statement.

C++
int& getValue() {
    int [1] = 5;
    return value;
}
Drag options to blanks, or click blank then click option'
Avalue
Bref
Cnum
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that does not match the return statement.
Not realizing returning a reference to a local variable causes undefined behavior.
4fill in blank
hard

Fill both blanks to create a reference to a string and modify it.

C++
std::string name = "Alice";
std::string& [1] = [2];
[1] = "Bob";
std::cout << name << std::endl;
Drag options to blanks, or click blank then click option'
ArefName
Bname
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same name for the reference and the original variable.
Not initializing the reference with the original variable.
5fill in blank
hard

Fill all three blanks to create a function returning a reference and use it correctly.

C++
int& [1](int& x) {
    return [2];
}

int main() {
    int a = 10;
    int& ref = [3](a);
    ref = 20;
    std::cout << a << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
AgetRef
Bx
Da
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching function name between declaration and call.
Returning a copy instead of a reference.