1

I just started C++ and I don't quite understand the difference between pass by value vs reference. It seems like the mechanisms are the same. For example, by passing a value in a function, I am told that I am passing by value. The function creates a "copy" of my argument(s) and it just exists in the scope of the function. When I pass by reference, it is not the same thing?

void square(int &x) {
    x *= x;
}

int main() {
    int a = 3;
    square(a);
    std::cout << a << std::endl; // prints 9
    return 0;
}

In this example, my function receives an address of an integer as an argument. This address is "copied" somewhere in memory, let's say &x = 0x1. This function is only aware of &x and not x, so when I call x, I'm calling *(&x) which is *(copy of &x) which is the original x. What I'm asking is basically is passing by reference simply pass by value of the address?

frank
  • 21
  • 1
  • 1
    I think you may be confusing different meanings of `&`. The fact that `T&` as a type denotes and a reference to `T` is unrelated to the address-of operator `&`. At the language level, references are not pointers; they're aliases for names. – Brian61354270 Mar 15 '23 at 02:37
  • *is passing by reference simply pass by value of the address* -- No. The term `reference` has a specific meaning in C++. What you are speaking of is passing the address of the entity, which is not the same as passing a reference to the entity. Maybe the confusion is using the word `reference` as some other computer languages use it. – PaulMcKenzie Mar 15 '23 at 02:37
  • `void square(int *x) { *x *= *x; }` -- `int a=3; square(&a);` -- That is different than your example. The `&` in this example means `address-of`, not `reference`. They are different things, but use the same symbol `&`. This example passes the pointer by-value. – PaulMcKenzie Mar 15 '23 at 02:42
  • Incidentally, while _is passing by reference simply pass by value of the address_ is false in terms of C++ as a language, it is generally true in terms of what the compiled program does at runtime. Compilers generally implement references as pointers. If you take a look at the assembly generated for `square`, it will probably be identical to the assembly generated for the same function accepting an `int*` instead. – Brian61354270 Mar 15 '23 at 02:44
  • Try calling it with `square(2)`. If the argument is accepted by (non-`const`) reference, as in your example, `square(2)` gives a diagnosable error (since a literal value `2` cannot be passed as a non-`const` reference). If the argument is passed by value, the call `square(2)` will compile but (since changes to arguments passed by value aren't visible to the caller) the function will have no effect on the caller. – Peter Mar 15 '23 at 05:36

0 Answers0