#include // assert #include // std::cout /* * pass an integer argument by value */ void pass_by_value(int n) { std::cout << "pass_by_value(" << n << ").\n"; n = 5; } /* * pass an integer argument by reference, using a pointer */ void pass_by_reference_a(int* pointer_to_n) { std::cout << "pass_by_reference_a(" << pointer_to_n << ").\n"; assert(pointer_to_n != nullptr); // often a good idea to check *pointer_to_n = 5; } /* * pass an integer argument by reference, using a pointer * * note: the int is passed by reference, but the int* is passed by value */ void pass_by_reference_b(int* pointer_to_n) { std::cout << "pass_by_reference_b(" << pointer_to_n << ").\n"; assert(pointer_to_n != nullptr); // often a good idea to check pointer_to_n = nullptr; // make the pointer point to the address 0 } /* * pass an integer argument by reference, using a reference */ void pass_by_reference_c(int& n) { std::cout << "pass_by_reference_c(" << n << ").\n"; n = 5; } int main() { int k{}; int* pointer_to_k = &k; // pass k = 4 by value // k = 4; pass_by_value(k); std::cout << "\tk = " << k << ".\n\n"; // pass k = 4 by reference, using a pointer value (memory address &k) // the code dereferences the pointer and writes 5 into its address // k = 4; pass_by_reference_a(pointer_to_k); std::cout << "\tk = " << k << ".\n\n"; // pass k = 4 by reference, using a pointer value (memory address &k) // the code assigns a new memory address to the pointer // note that the pointer is being passed by value // k = 4; pass_by_reference_b(pointer_to_k); std::cout << "\tk = " << *pointer_to_k << ".\n\n"; // pass k = 4 by reference, using a reference // // this is equivalent to using a pointer, except that it hides the // referencing and dereferencing from the programmer; accessing the // reference "looks like" accessing the variable // k = 4; pass_by_reference_c(k); std::cout << "\tk = " << k << ".\n\n"; }