SLIDE 2 Parameter Passing and Pointers Parameter passing and functions I: reference parameters call-by-value vs call-by-name
Call by name (not C++)
◮ consider:
f( .. ) { g(int y) { int x; : : ... g(x) ... } : }
◮ contrast to a call-by-name semantics for function calls:
◮ the function call g(x) causes f’s variable x to become an input parameter
variable of the function g
◮ g’s y and f’s x do not remain distinct variables ◮ if g alters its input parameter variable, it will alter f’s variable x also. Parameter Passing and Pointers Parameter passing and functions I: reference parameters call-by-value vs call-by-name
call-by-value illustration
main() { int b, r; b = 2; r = power(b,2); cout << b << ’ ’ << r << ’\n’; b = 3; r = power(b,3); cout << b << ’ ’ << r << ’\n’; } int power(int input, int n) { int m; m = input; input = 1; for (int i = 1; i <= n; i = i + 1) { input = input * m; } return input; }
◮ When you run this code, you should see:
2 4 3 27
◮ main has b
power has input power called with power(b,2) value of b passed to power’s input. power does lots of updates to input but back in main, b has not changed.
Parameter Passing and Pointers Parameter passing and functions I: reference parameters call-by-name by using reference parameters
call-by-name
◮ call-by-name behaviour can be stipulated by using reference parameter
- syntax. For any type T, a function can declare a parameter to have type
T&. T and T& are not really different types: its just telling the compiler about what semantics to use for parameter passing.
◮ f( .. ) {
g(int& y) { int x; : : y = ... ... g(x) ... : : } }
◮ g behaves as if it has been handed f’s variable x ◮ so once g has finished, the value of f’s variable x will have changed.
Parameter Passing and Pointers Parameter passing and functions I: reference parameters call-by-name by using reference parameters
call-by-name illustration
int power(int& input, int n); main() { int b, r; b = 2; r = power(b,2); cout << b << ’ ’ << r << ’\n’; b = 3; r = power(b,3); cout << b << ’ ’ << r << ’\n’; } int power(int& input, int n) { int m; m = input; input = 1; for (int i = 1; i <= n; i = i + 1) { input = input * m; } return input; }
◮ When you run this code, you should see:
4 4 27 27
◮ main has int b
power has int& input power called with power(b,2) in power input works as if it were b so back in main, b’s value has changed.