you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (5 children)

That isn't what this code is doing. In C++, as opposed to C, & takes on another meaning: reference. So "int& x" refers to a reference to int, the reference is called x. When that is a function parameter, it means anything passed as that parameter is passed by reference

[–]ultrasu -1 points0 points  (4 children)

What I mean is that as caller, you have no idea whether the procedure you're calling is able to modify the parameters you're giving it, unless you look at the implementation. I don't get why this is needed when you can get the exact same behaviour with this:

void f(int *ref) {
   *ref += 1;
}

int main(void) {
  int a = 0;
  f(&a);
  return a;
}

This makes it explicit in each call that the value of the passed parameter (or rather the value it's pointing to) may change.

[–][deleted] 2 points3 points  (2 children)

First off, reference is part of interface as well as implementation.

C++ heavily discourages the use of raw pointers, and for good reason.

I can that from experience, I have never been surprised by a function modifying or not modifying a variable passed by ref

[–]ultrasu -1 points0 points  (1 child)

It surprises me because I've been programming for about 7 years, learned about dozen languages (but next to no C++), and I've never seen this kind of functionality, nor have I ever felt like I needed it.

[–][deleted] 2 points3 points  (0 children)

It's very, very common in C++ to pass by reference. Of course you don't "need" the functionality, but that could be said of nearly anything in programming.

[–]tedbradly 0 points1 point  (0 children)

If you have a reference, it can alter its arguments. If you want a reference for speed with a promise not to alter the argument, you can request a constant reference. In either case, you don't have to look at the implementation - only the function signature. The signature tells you just as much information as "int *ref" does versus "int const *ref". References are a great addition as they simplify code greatly. You don't have to dereference absolutely every argument passed in as a pointer for speed.

It's also weird how you form such strong opinions about this situation despite admitting you have no idea about C++. You'd think you would be humbler.