Possible Duplicate:
What's the difference between passing by reference vs. passing by value?
I read that in C arguments are passed by value, but what’s is the difference between passing arguments by value (like in C) or by refencence (like C++ – C#)?
What’s the difference between a pointer and a reference?
void with_ptr(int *i)
{ *i = 0; }
void with_ref(int &i)
{ i = 0; }
In these cases are modified both value? If yes, why C++ allows to pass arguments by reference? I think it is not clear inside the function that the i value could be modified.
If you pass by value, changes to the variable will be local to the function, since the value is copied when calling the function. Modifications to reference arguments will propagate to the original value.
The difference is largely syntactic, as you have seen in your code. Furthermore, a pointer can be reassigned to point to something else (unless it’s declared
const), while a reference can’t; instead, assigning to a reference is going to assign to the referenced value.On the contrary, it’s absolutely clear: the function signature tells you so.
There’s actually a case to be made that it’s not clear outside the function. That’s why original versions of C# for instance mandated that you explicitly annotate any by-reference calling with
ref(i.e.f(ref x)instead of plainf(x)). This would be similar to calling a function in C++ usingf(&x)to make it clear that a pointer is passed.But in recent versions of C#, the use of
reffor calling was made optional since it didn’t confer enough of an advantage after all.