3

If we write the following in Qtas an argument to a function: QString &tableName

Does that mean we are passing by reference?

Thanks.

4
  • & returns the adres of your variable, right?
    – Kevin
    Jun 8, 2011 at 12:53
  • 2
    @Kevin Not in this case.
    – user2100815
    Jun 8, 2011 at 12:58
  • @Neil: Could you explain what it means in this context? I'm confused!
    – Kevin
    Jun 8, 2011 at 13:10
  • @Kevin It's a reference.
    – user2100815
    Jun 8, 2011 at 13:19

4 Answers 4

6

Strictly speaking, that is a function parameter, not a function argument. The parameter is the variable declared inside the function's parameter list; the argument is the value passed to the function by the calling function. So parameter QString &tableName is passed by reference. But as a function argument, &tableName would mean "the address of tableName".

Updated: As requested, here is a code sample to clarify the distinction:

void f (double y) ;
f (99.0) ;

double y is a parameter declaration; it resembles a variable declaration. y is a function parameter.

99.0 is a function argument; it is an expression, that must be convertible to type double.

3
  • Is there some well-defined terminology for the case?
    – vines
    Jun 8, 2011 at 13:29
  • I mean, where does the described difference between 'parameter' and 'argument' originate from? Is it some sort of convention, or it has some firmer ground?
    – vines
    Jun 8, 2011 at 13:48
  • 2
    If I remember correctly, the distinction has been around since Kernighan & Richie (if you're under 50, see en.wikipedia.org/wiki/The_C_Programming_Language).
    – TonyK
    Jun 8, 2011 at 16:52
5

Yes, this is pass-by-reference in C++. You could also write QString const & tableName, if you don't want to have the very possibility of accidentally changing tableName.

2
  • You can equivalently write const QString &tableName.
    – rubenvb
    Jun 8, 2011 at 13:00
  • @Rob, that's a pure accident :D
    – vines
    Jun 8, 2011 at 13:00
4

Yes. Tip: make it const if you don't want it to change.

2

Note that, like most non-trivial Qt basic types, QString is a lightweight container object that implements "copy on write" semantics. So the only reason to pass one by reference is if your function wants to modify the caller's copy, and there is never any reason to pass one by const reference (unless you do not know much about Qt).

2
  • That is largely a matter of taste. Jun 8, 2011 at 13:40
  • 1
    I'd say there's more than taste against this. Thread-safe "Copy on write" requires atomic counters, which may be far less efficient than just passing a reference.
    – vines
    Jun 9, 2011 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.