Local Variables & Function Arguments
Local Variables
Section titled “Local Variables”- They only exist inside a scope.
- scope: Defined within a pair of braces.
{ // start of scopeint i; // allocate memory for i... // use i} // end of scope, release memory used by i
Pass By Value
Section titled “Pass By Value”- 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 funcreturn y; // copies y into the function's return value}
Pass By Address
Section titled “Pass By Address”- 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
Pass By Reference
Section titled “Pass By Reference”- Acts like a pointer which is automatically dereferenced when used.
void func(int &y) { // y will be a reference to the caller's variable xy = 1;}int x = 0;func(x) // x will now have the value 1
Pass By Const Reference
Section titled “Pass By Const Reference”- 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