/* * It's worth noting that reference variables must be initialized when they are * declared. Further, once you initialize a reference variable, you can't * change which variable it refers to. * * Some examples that won't compile: * int &ref_i; // BAD - can't declare reference type without initialization * int &x = 5; // BAD - reference variables have to refer to other variables! * * int z; * double &ref_to_z = z; // BAD - types don't match * * The below shows an example that works */ void reference_variable_examples(){ int x = 5; int y = 6; int &ref_x = x; //declare a reference to x int &ref_y = y; //declare a reference to y ref_x = ref_y; // update the value of ref_x (and so the value of x) // to be the value of ref_y (which is the value of y) std::cout << x << std::endl; // prints 6 ref_y = 7; // updates the value of ref_y (and y) std::cout << y << std::endl; // prints 7 std::cout << x << std::endl; // prints 6 x = 8; std::cout << ref_x << std::endl; //prints 8 }; /* * Now we will have an example of a function that uses a reference parameter * note that x is not returned, you would expect x to not be impacted * after this function, but the reference parameter changes that. * */ void function_ref_params(int &x) { std::cout << "&x = " << &x << endl; x++; } /* This function calls the one above */ void call_ref_funct() { x = 1; std::cout << "x = " << x << endl; std::cout << "&x = " << &x << endl; function_ref_params(x); std::cout << x << endl; }