Skip to content

Local Variables & Function Arguments

  • They only exist inside a scope.
    • scope: Defined within a pair of braces.
    { // start of scope
    int i; // allocate memory for i
    ... // use i
    } // end of scope, release memory used by i
  • By default, a variable which is passed into a function is copied, as is it’s return value.
  • This is effectively taking double the memory, as memory is consumed by the original variable and the one copied from it.
    int func(int y) { // y is a copy of what is passed into func
    return y; // copies y into the function's return value
    }
  • Involves declaring the function parameter as a pointer, and then supplying the function with a reference to the original variable.
  • No double allocation of memory is involved.
    void func(int* y) { // y will be a pointer to the caller's variable x
    *y = 1;
    }
    int x = 0;
    func(&x); // x will now have the value 1
  • Acts like a pointer which is automatically dereferenced when used.
    void func(int &y) { // y will be a reference to the caller's variable x
    y = 1;
    }
    int x = 0;
    func(x) // x will now have the value 1
  • For read-only access to class objects, usually more efficient than pass by value.
    class MyClass {...};
    void func(const MyClass &mc) { // mc will be a reference to the caller's object
    // do stuff
    }
    MyClass my_class;
    func(my_class) // pass object to func