Wednesday, 28 February 2018

c++ - What's the difference between passing argument by value and by reference?











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.


Answer




what's is the difference between passing arguments by value or by reference




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.





What's the difference between a pointer and a reference?




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.




I think it is not clear inside the function that the i value could be modified.





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 plain f(x)). This would be similar to calling a function in C++ using f(&x) to make it clear that a pointer is passed.



But in recent versions of C#, the use of ref for calling was made optional since it didn’t confer enough of an advantage after all.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...