/* Pass-by-reference and passing a pointer by value * are slightly different */ #include using namespace std; // difference between pass by reference and // passing a pointer by value. // Pass-by-reference offers more control, in a sense. // Any time we set the value of a, we are affecting the // variable in the calling code whose address we were sent. void f( int &a ) { a = 3; } // But with C, we can stop referring to the variable in the calling // code if we assign to the pointer value. void g( int *a ) { // Here is the use that is analogous to the pass-by-reference // *a = 3; // Here is the alternate use // int *y = (int*)malloc( sizeof(int) ); // *y = 5; // a = y; // *a = 7; // free(a); } int main () { int a = 1; cout << "Before f, a = " << a << endl; f( a ); cout << "After f, a = " << a << endl; a = 1; cout << "Before g, a = " << a << endl; g( &a ); cout << "After g, a = " << a << endl; return 0; }