Search code examples
c++pass-by-reference

Pass by reference notation


My question is really straightforward and I believe understandable. I've made this simple snippet to illustrate my conflict when I'm passing values by reference.

int main() {
 int a = 1;
 int &b = a;
}

I know that this is the correct way to do it but how does it make sense to take the address of b and make it equal to the value of a. Logically it should be: int &b = &a;


Solution

  • Many operators are context-sensitive. The & "operator" could mean three different things depending on context:

    1. It could be used when defining a reference

      int& r = a;  // The variable r is a reference of the variable a
      
    2. It could be used to get a pointer to something

      int* p = &a;  // Here & is the address-of operator which returns a pointer
                    // Here it makes p point to the variable a
      
    3. It could be the bitwise AND operator

      0x53 & 0x0f    // Here's a bitwise AND operation, the result is 0x03