we have afunction void writeout(int z, int k) {
cinn << z<<k;
cout >> z >> k;
void nn(int a, int &b){
writeout (a,b); //4,5
a++;
b++;
writeout (a,b);//5,6
}
int main (){
int d,s;
cin <d<<s;
wirteout (d,s); //4,5
nn(d,s,);
writeout (d,s,); //4,6,
}
som what is the problem, why is nn function now changing s from 5 to 6 and NOT changing d from 4 to 5 now?
Y, now we have this &b, but is the result right?
The difference is in the two function's declarators:
void writeout(int z, int k)
Here, both int z and int k are passed to the function by value. This means that a copy is made of these values to be used within the function. The original variables remain otherwise untouched.
void nn(int a, int &b)
Here, b is passed in by reference, meaning that instead of making a copy of the original variable, you are actually passing in the memory-address of the original variable. This means that when you make changes to it (like b++), the original variable (in main()) will be changed.
Please see this page for further information: http://www.cplusplus.com/doc/tutorial/functions2/