Pass by Reference

Passing a value by reference allows the actual value outside of the function to be acted upon, as opposed to a copy of the value.


In passing a value by reference, C++ differs from C in that it allows any type of reference to be used (as opposed to just a pointer reference in C).


Accordingly, C++ allows values to be passed in using their normal identifier, and are then accepted within the formal parameter list of the function using the ampersand & (address of) reference operator:


Compile & Run:

a and b in main before swap: 17, 42
x and y in myFunc: 42, 17
a and b in main: 42, 17


Notice the swap of the values within the function has also affected the values in main()

Leave a Reply