142k views
2 votes
How do we pass by reference in C++:

A. pass_by_reference(int &var)
B. pass_by_reference(int *var)
C. pass_by_reference(int var)
D. pass_by_reference(&var)

User Srboisvert
by
8.1k points

1 Answer

0 votes

Final answer:

In C++, to pass a variable by reference, use the syntax A. pass_by_reference(int &var). This allows the function to modify the original variable directly, unlike passing by value which creates a copy.

Step-by-step explanation:

To pass a variable by reference in C++, you would use the syntax where the function parameter is a reference type, denoted by an ampersand (&) before the variable name. The correct option for passing a variable by reference is A. pass_by_reference(int &var). In this case, the function will receive a reference to the variable passed to it, allowing the function to modify the original variable.

Option B. pass_by_reference(int *var) passes a pointer to the variable, which also allows the original variable to be modified, but through dereferencing the pointer. Option C. pass_by_reference(int var) passes the variable by value, creating a copy of the argument within the function scope. Option D. pass_by_reference(&var) is incorrect syntax; the ampersand outside of a function declaration is used to obtain the address of a variable, not to pass it by reference.

User Graham Chiu
by
7.8k points