[amp_mcq option1=”by reference” option2=”by value” option3=”globally” option4=”locally” correct=”option2″]
The correct answer is: B. by value
When you pass a variable by value, C++ creates a copy of the variable’s value and passes the copy to the receiving function. The receiving function can then modify the copy, but the original variable will not be affected.
For example, consider the following code:
“`c++
int main() {
int x = 10;
change_value(x);
return 0;
}
void change_value(int x) {
x = 20;
}
“`
In this code, the variable x is passed by value to the function change_value(). When change_value() modifies the value of x, it is only modifying the copy of x that was passed to the function. The original variable x is not affected.
Passing a variable by value is useful when you want to pass a copy of the variable’s value to a function, but you do not want the function to modify the original variable.
The other options are incorrect for the following reasons:
- Option A: When you pass a variable by reference, C++ passes the address of the variable to the receiving function. The receiving function can then modify the variable’s value directly.
- Option C: A variable is declared globally when it is declared outside of any function. A global variable can be accessed from any function in the program.
- Option D: A variable is declared locally when it is declared inside of a function. A local variable can only be accessed from within the function in which it is declared.