Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Call by Value and Call by Reference in C++ ( With Examples )

Call by Value and Call by Reference in C++ ( With Examples )

21 May 2024
Intermediate
50.5K Views
14 min read
Learn with an interactive course and practical hands-on labs

Free C++ Foundation Course: Learn C++ In 21 Days

Call by Value and Call by Reference in C++: An Overview

If you're new to coding, you might have not heard of Call by Value and Call by Reference in C++ programming language. In this blog post of C++ tutorial, we're going to take a look at the basics of both concepts in C++. You can also explore C++ online training so that even novice coders can better understand them. We'll also discuss when it's best to use one or the other while writing the code in C++, ensuring that your program runs efficiently and correctly.

Ways of Passing Data to a Function

We have already seen functions and their various aspects like formal parameters and actual parameters in the section, Functions in C++. In the function call, we used to pass parameters/arguments/data to the function that is being called.

There are two ways to pass the data to a function in the C++ language:

  1. call by value
  2. call by reference

functions in c++ programming

Read More - C++ Interview Questions Interview Questions for Freshers

Call by Value in C++

In this method, the value of the actual parameteris passed to the corresponding formal parameter of the called function. This technique ensures that the original data i.e. actual parameter does not get altered by the called function, as the called function deals only with a copy of that data.

When a programmer opts for the call by value, the memory space for the formal parameters is allocated separately in the function stack, which further reinforces the fact that the original data remains untouched. Thus, formal parameters and actual parameters are allocated to different memory locations.

When to use Call by Value in C++

  • When you do not want to change the actual parameters of the function.
  • When you want to make copies of the data instead of the actual data.
  • When space is not an issue.
  • Usually, when you do not deal with recursion or backtracking.

Call by Value in C++ With Example


#include <iostream>
using namespace std;

void swap(int x, int y) {
 int temp = x;
 x = y;
 y = temp;
}

int main() {
 int a = 40;
 int b = 50;
 cout << "Before swap: a = " << a << " b = " << b << endl;
 swap(a, b);
 cout << "After swap: a = " << a << " b = " << b << endl;
 return 0;
}

The above program in C++ Compiler swaps the values of the variables, a and b. In the main() function, the function call passes the actual parameter values i.e. values of a and b to the swap() function. The swap() function swaps the values of a and b.

Due to the call by value method, the value of the original variables a and b remains unchanged even after swapping by the swap() function.

Output

Before swap: a = 40 b = 50
After swap: a = 40 b = 50

Advantages of Using Call by Value in C++

  • This method does not change the original variable. In other words, it is preserving data.
  • Whenever a function is called, it does not ever impact the actual contents of the actual arguments.
  • Here, the value of actual arguments passes to the formal arguments. Therefore, any changes made in the formal argument do not impact the real cases.

Disadvantages of Using Call by Value in C++

  • Data passed is stored in temporary memory.
  • You can’t operate over the actual data but rather on a temporary copy of the data, because of which changes made in the data in the function are not reflected in the main() function.
  • Memory space required while using string, array, vector, etc can be huge.
  • Solving backtracking and recursion can be complex using call-by-value.

Call by Reference in C++

In this method, instead of passing the values of the actual parameters to the formal ones, the addresses of the actual parameters are passed. Therefore, the modification by the called function to the formal parameters affects the actual parameters as well.

When a programmer opts for the call by reference, the memory space for the formal parameters and the actual parameters are the same. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.

This technique not only conserves memory but also simplifies collaboration, as complex data types like arrays or structures can easily be manipulated without being duplicated needlessly.

When to use Call by Reference in C++

  • When the programmer wants to modify the original value of a variable within a function and have those modifications reflected in the calling code.
  • Suppose, you have a large object (e.g., a complex data structure or a class instance) and you want to avoid the overhead of copying it.
  • When you need to modify the function parameters themselves, rather than just the values they represent.
  • when working with large data, since passing by reference does not create a copy of the data. It increases efficiency.

Call by Reference in C++ Compiler With Example

#include <iostream>
using namespace std;
void swap(int *a, int *b) {
 int temp = *a;
 *a = *b;
 *b = temp;
}
int main() {
 int x = 5;
 int y = 10;
 cout << "Before swap: x = " << x << " , y = " << y << endl;
 swap(&x, &y);
 cout << "After swap: x = " << x << ", y = " << y << endl;
 return 0;
}

In the above program of swapping two numbers, the main()function passes the address of the two variables, a and b as actual parameters in the function call denoted by the reference operator &.

The swap() function uses the pointer to get the value of the variables whose addresses are passed by the function call. After swapping the values, the value of the actual parameters gets permanently modified as the address of the variables is passed.

Output

Before swap: x = 5, y = 10
After swap: x = 10, y = 5

Advantages of Using Call by Reference in C++

  • The function can change the value of the argument. Thus, it is very beneficial.
  • It does not create duplicate data for holding values which helps in saving the memory space.
  • It helps in avoiding changes that occur by mistake.
  • A person who reads the code is not aware that the value can be modified in the function.

Disadvantages of Using Call by Reference in C++

  • A function taking in a reference requires ensuring that the input is non-null. Thus, a null check is not supposed to be made. Thus, it has a non-null guarantee.
  • Passing by reference makes the function not pure theoretically
  • With references, a lifetime guarantee is a big problem. It is particularly dangerous when working with lambdas and multi-threaded programs.

Difference between Call by Value and Call by Reference in C++

AspectCall by ValueCall by Reference
What is passedCopies the actual value of the argument.Passes a reference or memory address of the argument.
Modification of argument Changes made to the parameter inside the function do not affect the original argument.Changes made to the parameter inside the function directly affect the original argument.
Memory Usage Typically consumes less memory as it creates a separate copy of the argument.May consume more memory as it uses references to the original data.
Performance Generally faster due to the smaller data transfer.May be slower due to the need to access data through references.
Data Type Constraints Suitable for simple data types (int, float, etc.).Suitable for complex data types (arrays, objects, etc.).
Risk of unintended changes Reduces the risk of unintentional side effects.Increases the risk of unintentional side effects.
Summary

call by value and call by reference in C++ are important concept to understand if you want a deeper conceptual understanding of computer programming. call by value copies a variable's value whereas call by reference passes a pointer instead. Depending on what the output is supposed to be, developers need to decide which one they should use.

Consider enhancing your knowledge and gaining recognition by enrolling in C++ Certification Training, which will provide comprehensive guidance and hands-on experience in mastering various concepts and techniques in C++ programming.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this