a pointer variable is a variable that contains the address of a memory location. a reference variable is an alias for a variables address (&<variable name>). when used in an expression, is the same as a pointer (*<variable name>).
a pointer variable is a value type the size of an address.
the compiler decides if a reference variable takes memory (no need, its an alias to a real variable).
void swap(int& x, int& y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
}
int main () {
int a = 100;
int b = 200;
int& c = a; //c is alias for a
c = 300; // a = 300;
// pass a & b by reference
swap(a, b); //a = 200, b = 300
}
void swap(int* x, int* y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
}
int main () {
int a = 100;
int b = 200;
int *c = &a; // c pointer to a
*c = 300; // a = 300
// pass a & b by address
swap(&a, &b); //a = 200, b = 300
}