Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the value 10 instead of the variable name.
Using pointer syntax like &x or *x.
✗ Incorrect
A reference must be initialized with a variable name, not a value or pointer.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the array name instead of an element.
Returning a pointer instead of a reference.
✗ Incorrect
Returning arr[0] returns a reference to the first element, matching the return type.
3fill in blank
hardFill 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'
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.
✗ Incorrect
The local variable must match the returned reference name; however, returning a reference to a local variable is unsafe.
4fill in blank
hardFill 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'
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.
✗ Incorrect
The reference variable refName refers to the string variable name, so modifying refName changes name.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching function name between declaration and call.
Returning a copy instead of a reference.
✗ Incorrect
The function getRef returns a reference to x, and calling getRef(a) returns a reference to a, allowing modification.