Concept of Value and Reference
there are two ways to represent a variable: by value and by reference.
When a variable is passed by value, a copy of the variable is created and passed to the function. Any changes made to the copy do not affect the original variable. Here's an example:
int main() {
int a = 5;
int b = 10;
swapByValue(a, b);
std::cout << "a: "
<< a << " b: "<< b<<std::endl;
return 0;
}
void swapByValue(int x, int y){
int temp = x;
x = y;
y = temp;
}
Here, the variables a
and b
are passed by value to the swapByValue
function. The function swaps the values of the passed variables, but the values of a
and b
in the main function remain unchanged. The output will be "a: 5 b: 10".
On the other hand, when a variable is passed by reference, a reference to the original variable is passed to the function. Any changes made to the variable inside the function will affect the original variable. Here's an example:
int main() {
int a = 5;
int b = 10;
swapByReference(a, b);
std::cout << "a: "
<< a << "b: "<< b<<std::endl;
return 0;
}
void swapByReference(int &x, int &y){
int temp = x;
x = y;
y = temp;
}
Here, the variables a
and b
are passed by reference to the swapByReference
function. The function swaps the values of the passed variables, and the values of a
and b
in the main function are also changed. The output will be "a: 10 b: 5".
It's worth noting that in C++, when an object is passed by value, a copy of the object is created, but when an object is passed by reference, a reference to the original object is passed.