C++Introduction to C++Learn C++

Learn About Parameters Passed by Reference in Functions

In the functions that we created in previous posts, their parameters have always been passed by value. This means that, when we call a function, what is passed to the function are the values of these parameters on that moment of the call. Variables are copied into the variables represented by the function parameters. Let’s remember an example,

Here x and y values are copied to a and b parameters and returned with addition.

We can access to its parameters directly by using its parameters as references. In C++, references are indicated with an ampersand (&) following the parameter type, it points the address of the variable. So we can modify our function parameters as a reference parameters by using & character before their variable names.

Here we passed x and y by itself, and we didn’t do copy operation on a & b variables of our function. If a variable is passed by reference that means it is passed without a copy operation, just addressing the variable itself. The variable identified by the function parameter, becomes somehow associated with the argument passed to the function. This allows users to do modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call. Referencing is important to eliminate copy operations and speeds up functions.

Get started building powerful apps with C++Builder!


Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

Related posts
C++Learn C++Videos

Learn C++ With Monoids, Monads, and Applicative Functors: Repeated Software Patterns (CPPCon 2020) Video

C++Learn C++Videos

Learn C++ With Pipes: How Plumbing Can Make Your C++ More Expressive by Jonathan Boccara (CPPCon 2020) Video

C++Introduction to C++Learn C++

Learn Classes and Objects in C++

C++C++11C++14C++17Introduction to C++Learn C++

Learn about Access Specifiers in C++ Classes

Worth reading...
Learn to Use Parameters in Functions in C++