Refference traslation

Hello!
I do not understand one thing:

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?

Many thanks!
closed account (o3hC5Di1)
Hi there,

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/

All the best,
NwN
Hello!
Many thanks!
Please, can someone write me the most simple code examle?
Many thanks!
Doesn't the tutorial (that NwN did link to) contain simple examples?
Topic archived. No new replies allowed.