Passing by Reference

​Using Reference Variables as Parameters

  • A mechanism that allows a function to work with the original argument from the function call, not a copy of the argument

  • Allows the function to modify values stored in the calling environment

  • Provides a way for the function to ‘return’ more than one value

Passing by Reference

  • A reference variable is an alias for another variable

  • Defined with an ampersand (&)

    • void getDimensions(int&, int&);

  • Changes to a reference variable are made to the variable it refers to

  • Use reference variables to implement passing parameters by reference

Example

Reference Variable Notes

  • Each reference parameter must contain &

  • Space between type and & is unimportant • Must use & in both prototype and header

  • Argument passed to reference parameter must be a variable – cannot be an expression or constant

  • Use when appropriate – don’t use when argument should not be changed by function, or if function needs to return only 1 value

Last updated

Was this helpful?