Passing References. Different ways

Whats the difference between these 2 things

1
2
3
void addOne(int* i1){ i1 += 1; };
int n1 = 5;
addOne(&n1);


and this

1
2
3
void addOne(int& i1){ i1 += 1; };
int n1 = 5;
addOne(n1);


Im pretty sure both of those would work. changing n1 from 5 to 6. but why 2 ways? whats the advantages and disadvantages of each?
When we call a function the "normal" way, like this:

 
Function (a);


A copy of the value in the variable a is passed into the function.

If we pass in an argument with the "address of" operator (&) then we pass in the memory address of that variable to the function.

And when we use the de-reference operator (*) then we pass a pointer to the variable into the function.
Not the best at explaining this one, :P
In the first function, you pass a pointer to an integer. This means that you will not send the actual value, but the memory address in which this is stored. http://www.cplusplus.com/doc/tutorial/pointers/

In the second function, you pass a reference to an integer. This means that you send a "simpler pointer", that tells that i1 is a way to call the variable outside the function that is passed to it.


You are right that both should work, but they don't have the same functionality at this moment. For the first function to work, you will have to do this:
1
2
3
4
5
void addOne(int* i1){ *i1 += 1; }; // Send a pointer and change the value to which it points (*i1)
...
int n1 = 5;
addOne(&n1);
...
Recently I have read that,

First method is old "C" style method of passing reference

Second method is generally used in C++ to pass reference
http://www.cplusplus.com/forum/articles/20193/

Read the first part entitled "Difference between references and pointers".
Recently I have read that,

First method is old "C" style method of passing reference

Second method is generally used in C++ to pass reference
Tell me the source of where you read that, this is absolutely not true.
In C, there was no other method than to pass a pointer if you wanted to modify the original object (or avoid copies).
In C++ references are an additional option. You generally use a pointer when the argument is optional (that is to say, it may be 0) and a reference otherwise.
jsmith that was a good read.
Topic archived. No new replies allowed.