Returning a reference in C++
Level 3120 keystrokes
getRef returns int&, a reference to arr[i] rather than a copy of its value, so the call can stand on the left of =. Assigning 99 changes nums[1].
C++ code
// int& return type: returns the element itself, not a copy; arr[] is really a pointer to the caller's array1int& getRef(int arr[], int i) { // Returning a reference is safe here because the array outlives the call2 return arr[i];3}4 5int nums[] = {1, 2, 3};// The call refers to nums[1], so this assigns 99 to it6getRef(nums, 1) = 99;// Prints 997cout << nums[1] << endl;Output
99
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
,× 4;× 4[× 4]× 4<× 4(× 2)× 2{× 2}× 2=× 2