/* C++ supports pass-by-reference for parameter passing during function calls. * This is sort of an automatic pass-by-value-with-pointers. * In the function signature, you indicate that a parameter is pass-by-reference using the &. * When calling the function, you just provide the name of the variable. * C++ automatically passes its address instead of its value (note the implication that this means the argument has to have an address and can't just be a literal value) * Then the function uses to the parameter without having to do any dereferencing * Here, we demonstrate with a swap function. * The swap functions's parameters a and b actually have their values stored in the stack frame for the main function. */ #include using namespace std; int c_thing( int a, int b ) { printf( "Hi\n" ); } // C++ has pass-by-reference int swap (int &a, int &b) { int tmp = a; // put the value of a into tmp a = b; b = tmp; printf( "in swap, a is at %p\n", &a ); printf( "in swap, b is at %p\n", &b ); printf( "in swap, tmp is at %p\n", &tmp ); return 0; } int main () { int a = 3, b = 5; printf("in main, a is at %p\n", &a ); printf("in main, b is at %p\n", &b ); cout << "Before swap a = " << a << ", b = " << b << "\n"; swap(a, b); // pass it the variables. cout << "After swap a = " << a << ", b = " << b << "\n"; // if we use pass-by-reference, we need to provide // a variable as input // If we use pass-by-value, we can use an expression or a literal // value. c_thing( 3+5, 2 ); //swap( 3+5, 2 ); // illegal return 0; }