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!

close

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.

About author

33+ years of coding with more than 30+ programming languages, mostly C++ on Windows, Android, Mac-OS, iOS, Linux and some other operating systems. Dr. Yilmaz Yoru was born in 1974, Eskisehir-Turkey. He graduated from the department of Mechanical Engineering of Eskisehir Osmangazi University in 1997. One year later he started to work in the same university as an assistant. He received his MSc and PhD degrees from the same department of the same university. He has married and he is a father of a son. Some of his interests are Programming, Thermodynamics, Fluid Mechanics and Artificial Intelligence. He also likes the graphical 2D & 3D design and high-end innovations.
Related posts
C++Introduction to C++Language FeatureLearn C++

How To Use The Comprehensive Form Properties In C++ VCL Apps

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

This Is How To Add Characters to Wide Strings in Modern C++

C++ComponentsLanguage FeatureLearn C++

How To Create Gorgeous Transparent App Windows With C++

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

This Is How To Get A Substring of a Wide String in C++

Worth reading...
Learn About the Main Function in C++
en_USEnglish