Complete the code to declare a function parameter that passes an integer by reference.
void increment([1] int &num) {
num++;
}The const keyword before the reference parameter means the function cannot modify the argument. Here, we want to pass by reference, so int &num is correct, and adding const is common to prevent changes.
Complete the code to call the function swap passing two integers by reference.
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;
}When passing by reference, you just pass the variable name without & or * in the call. The function parameter already expects a reference.
Fix the error in the function declaration to correctly pass a string by reference.
#include <string> void printName([1] std::string name) { std::cout << name << std::endl; }
Passing a string by const std::string & is efficient and prevents modification. It avoids copying the string.
Fill both blanks to create a function that doubles an integer passed by reference and call it correctly.
void doubleValue([1] int &num) { num *= 2; } int main() { int val = 7; doubleValue([2]); return 0; }
The function parameter should be int &num to pass by reference. When calling, just pass the variable val without &.
Fill all three blanks to create a function that swaps two integers by reference and call it correctly.
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; }
The function parameters should be int &a and int &b to pass by reference. When calling, just pass the variable x without &.