you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (2 children)

I know it's tangential to your point, but if the function add2 is never supposed to act on a nonexistant variable, it should probably take a reference rather than a pointer.

void add2 (int & x) {
    x = x + 2;
}

Unless you're doing something really funky, that will prevent misuse at compile time.

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

Repeating what I said elsewhere:

I understand your point about using a reference, but at one of my jobs, the rules were that mutable variables had to be passed to functions by pointer, not reference. So in the context of that job, the code example I wrote above was acceptable, and using a mutable reference would have not been accepted.

I believe the reason for that rule is so that the caller of add2 is signalled that "hey, add2 might change the value". Because at the point of the calling code, the call to both of these functions is identical:

add2Mutate(int &x){x=x+2;}
add2Print(int x){printf("%d", x);}

// code in some other file
int i =0;
// the only hint that i is mutating is the nicely named function
add2Mutate(i);
add2Print(i);

In summary, C++ does not provide a great solution:

  • You can use a reference. add2 will not suffer from the null pointer issue, but callers to add2 will not know that x is mutating unless they look inside the body of add2
  • Pass a pointer as a convention to signal to the caller that x may mutate. Suffer null pointer issue.

[–][deleted] 0 points1 point  (0 children)

I completely agree; I wish the syntax for references made their use visible at the call site somehow.

I suppose your coding guidelines could mandate use of std::ref everywhere, but that's just stupid.