Remark:
void func(int& x)
NOTE: get a copy, compile it and run it to see the effect !
The variable i in main() is incremented when func() returns !
Assume the following agreement: parameter passed in D0 parameter passed by reference C++ code: Assembler code: --------- -------------- main() main: { MOVE.L #i, D0 // pass addr int i; // of var i func(i); // pass addr BSR func ------+ // of var i .... | } | | void func( int& x ) func: <-----+ { // Assume addr is passed x = x + 1; // So D0 = address of param } // We have to go get the value... MOVE.L D0, A0 MOVE.L (A0), D1 // Now D1 = x ADD.L #1, D1 // D1 = x + 1 // Don't stop yet... // Program says: put x+1 in x ! MOVE.L D1, (A0) // Update !!! RTS
Assembler programming can help you understand "mysterious" concepts in computer science...
// func(x,y) computes x^2 + y^2 int func(int& x, int y) <---- x is passed by reference, y by value { x = x + 1; y = y + 1; return(x*x + y*y); } main() { int a, b, c; int i, j, k; c = func(a,b); k = func(i,j); }
main: MOVE.L #a, D0 // Pass param 1 by ref MOVE.L b, D1 // Pass param 2 by value BSR func MOVE.L D7, c // c = func(a,b) MOVE.L #i, D0 // Pass param 1 by ref MOVE.L j, D1 // Pass param 2 by value BSR func MOVE.L D7, k // k = func(i,j) .... .... func: MOVEA.L D0, A0 // D0 = address of variable x MOVE.L (A0), D2 // Now D2 = value of variable x ADD.L #1, D2 // Computed x+1 MOVE.L D2, (A0) // Stores: x = x + 1 MOVEA.L D1, A0 // D1 = address of variable y MOVE.L (A0), D2 // Now D2 = value of variable y ADD.L #1, D2 // Computed y+1 MOVE.L D2, (A0) // Stores: y = y + 1 MOVEA.L D0, A0 // D0 = address of variable x MOVE.L (A0), D2 // Now D2 = value of variable x MULS D2, D2 // D2 = x*x MOVEA.L D1, A0 // D0 = address of variable y MOVE.L (A0), D3 // Now D3 = value of variable y MULS D3, D3 // D2 = y*y ADD.L D3, D2 // x*x + y*y MOVE.L D2, D7 // Put return value in the agreed location RTS