The full code for this program (which includes code to display values of variables as the code executes) can be found in: ptrParamRetVal.cpp.
// Pass-by-reference (simple swap)
void swap1(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
// Simulated pass-by-reference (simple swap)
void swap2(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int a = 1, b = 2, c = 3, d = 4; swap1(a, b); swap2(&c, &d);
// Pass-by-value with: primitive type, pointer, array
void passByValue(int x, int *y, int z[]) {
x = 1;
y = new int;
*y = 2;
*z = 3;
z = new int[3];
y = new int[2];
*z = 4;
*y = 5;
}
int e[4], f[4];
for (int i = 0; i < 4; i++)
e[i] = 3*i;
// f = e; <---- assignment of arrays not allowed
for (int i = 0; i < 4; i++)
f[i] = e[i];
passByValue(a, &b, e);
// Pass-by-reference with: primitive type, pointer
// Note that body of function is same as body of passByValue
void passByRef(int &x, int * &y, int *z) {
x = 1;
y = new int;
*y = 2;
*z = 3;
z = new int[3];
y = new int[2];
*z = 4;
*y = 5;
}
// Pass-by-reference with pointers: good use vs. bad use
void passByRef2(int * &x, int * &y) {
int z[4];
z[0] = 3;
x = new int[2];
y = z;
}
// passByRef(a, &b, f); // nope
// passByRef(a, e, f); // nope
int *g = new int[4];
for (int i = 0; i < 4; i++)
g[i] = f[i];
passByRef(a, g, f);
int *p = new int;
int *q = new int;
*p = *q = 8;
passByRef2(p, q);
// Return value: primitive value
int returnVal1() {
int x = 4;
return x;
}
// Return value: pointer (bad use)
int *returnVal2() {
int x = 5;
return &x; // note: generates warning, but compiles
}
// Return value: pointer (good use)
int *returnVal3() {
int *x = new int;
*x = 6;
return x;
}
int aa, *bb, *cc; aa = returnVal1(); *bb = returnVal1(); bb = returnVal2(); cc = returnVal3();