Call by value makes a copy of the argument and puts it in a local variable for use by the function, so if the function changes the value of the local variable the argument itself is not changed. Call by reference passes a reference of the argument to the function rather than a copy, so if the function changes the value of the argument then the argument itself is changed.
The function prototype void change(int);
tells the compiler that there is a function named change which takes a single argument of type int
and returns void
(i.e. nothing). It is call by value since there is no &
with the argument. Later in your code you have the line change(orig);
which actually calls the function with argument orig
of type int
. Since the function prototype was declared before this function call the compiler recognizes it as a function.
Take a look at the output of this program:
#include<iostream>
using namespace std;
int main(){
void change(int);
void change2(int&);
int x = 10;
cout<<"The original value of x is: "<< x <<"\n";
change(x); // call change(), which uses call by value
cout<<"Value of x after change() is over: "<< x <<"\n";
change2(x); // call change2(), which uses call by reference
cout<<"Value of x after change2() is over: "<< x <<"\n";
return 0;
};
void change(int orig){
cout<<"Value of orig in function change() at beginning is: "<<orig<<"\n";
orig=20;
cout<<"Value of orig in function change() at end is: "<<orig<<"\n";
return;
}
void change2(int &orig){
cout<<"Value of orig in function change2() at beginning is: "<<orig<<"\n";
orig=20;
cout<<"Value of orig in function change2() at end is: "<<orig<<"\n";
return;
}
I've changed int orig
in main()
to int x
to hopefully avoid name confusion, and I've added change2()
which uses call by reference.