+ 1
Why was var changed? How does it work?
#include <iostream> using namespace std; void myFunc(int &x) { x = 100; } int main() { int var = 20; myFunc(var); cout << var; }
4 Respostas
+ 14
Conpare both:
void myFunc1(int &x) {
x = 100;
}
void myFunc2(int x) {
x = 100;
}
In myFunc1, variable x is passed via reference. This means that the address of the variable is passed into the function. Whatever changes made to the variable in the function will also be reflected in the main function.
In myFunc2, variable x is passed via value. This means that only the value of x is passed into the function. Changes made to the variable are not reflected in main.
+ 7
Hi Mark!
x's address is a parameter of myFunc (pass by reference), giving the function the ability to modify the value stored at that address.
+ 3
Parameter in myFunc () is a reference variable which read and access the address of the var on calling. The statement x=100 overwrites the existing value of var.
Hence the value of var changes.
+ 1
because & is used to store the memory address of the variable and the function changes the values at that address