Messing around with memory when parameter passing
The following code
#include ...
int veryBad = 25;
main() {
int i = 20, j = 30;
int a[5] = {1, 2, 3, 4, 5};
doIt(a, a[2], a[2], a[2], i, j);
cout << veryBad << " " << i << " " << j << endl;
for (int i = 0; i < 5; i++) {
cout << a[i] << " ";
}
cout << endl << endl;
return 0;
}
void doIt(int a[], int b, int c, int& d, int& e, int& f) {
veryBad = 35;
b = 2*e - 2;
++c;
d += 5;
e = (f < 0 ? c : b);
f = a[2];
a[2] = 5;
cout << b << " " << c << " " << d << " " << e
<< " " << f << " " << veryBad << endl;
for (int i = 0; i < 5; i++) {
cout << a[i] << " ";
}
cout << endl << endl;
}
produces the following output:
38 4 5 38 8 35
1 2 5 4 5
35 38 8
1 2 5 4 5
Memory for the above code is as follows:
+----+
global veryBad | 25 |
+----+
__ ----- ----- ----- ----- ----- ---- ----
main: a| -|--->| 1 | 2 | 3 | 4 | 5 | i| 20 | j| 30 |
-- ----- ----- ----- ----- ----- ---- ----
^ 0 1 ^ 2 3 4 ^ ^
/ \ / /
/ \ / /
+---/------------------\----------------/-------/---+
doIt: | | \ / / |
|+-|-+ +---+ +---+ +-\--+ +--/-+ +-/--+ |
|| | | | 3 | | 3 | | \ | | / | |/ | |
|+---+ +---+ +---+ +----+ +----+ +----+ |
| a b c d e f |
+---------------------------------------------------+
The arithmetic for the assignments:
veryBad = 35
b = 2*e - 2 which is 2*20 - 2 which is 38
++c which is 4
d += 5, which dereferenced is a[2] becomes the value of 8
e = (f < 0 ? c : b), f<0 is false, so e = b, which dereferenced is i,
which is now 38
f = a[2] which dereferenced is j becomes 8
a[2] = 5, so the 8 now becomes 5
At the end of the function, the memory now looks like
+----+
global veryBad | 35 |
+----+
__ ----- ----- ----- ----- ----- ---- ----
main: a| -|--->| 1 | 2 | 5 | 4 | 5 | i| 38 | j| 8 |
-- ----- ----- ----- ----- ----- ---- ----
^ 0 1 ^ 2 3 4 ^ ^
/ \ / /
/ \ / /
+---/------------------\----------------/-------/---+
doIt: | | \ / / |
|+-|-+ +---+ +---+ +-\--+ +--/-+ +-/--+ |
|| | | | 38| | 4 | | \ | | / | |/ | |
|+---+ +---+ +---+ +----+ +----+ +----+ |
| a b c d e f |
+---------------------------------------------------+