×

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages.

C++ Function

A function is a set of statements that executes a task. It executes only when it is called. In C++, functions are categorized into two different categories on behalf of argument (parameter) pass.

  • Function with parameter (return_type function_name(paramenter);)

A function that takes a parameter in a function is called a function with a parameter.

  • Function without parameter (return_type function_name();)

A function that does not take a parameter in the function is called a function without a parameter. Here, we can see the working of C++ functions.

Function with a parameter has further categorized into two different categories. These categories are Call by Value and Call by Reference. Here, we will discuss only Call by Value.

C++ Call by Value

When a function is called, new elements are created in the stack memory to store essential data about the function, including allocated memory for parameters, local variables, and the return value. The Call by value method enables us to copy an actual parameter into a formal parameter. If we wish to modify the value of the function parameter, it is changed only for the current function. It means that any changes nside the parameter do not affect the original variables. It is also known as pass by copy or call by value.

Example:

Let us take an example to illustrate the Call by Value in C++.

#include<iostream>

using namespace std;

void swap(int,int);

int main()

{

int a=5,b=10;

cout<<"Before swapping
Value of a is :"<<a<<"
Value of b is :"<<b;

swap(a,b);

cout<<"
Outside function after swapping
Value of a is :"

<<a<<"
Value of b is "<<b;

return 0;

}

void swap(int a,int b)

{

int temp;

temp=a;

a=b;

b=temp;

cout<<"
Value inside function after swapping
Value of a is

:"

<<a<<"
Value of b is :"<<b;

}

Output:

Before swapping

Value of a is : 5

Value of b is: 10

Value inside function after swapping

Value of a is :10

Value of b is :5

Outside function after swapping

Value of a is : 5

Value of b is: 10

Explanation:

Before the Function Call:

  • In this example, we declared two integer variables, a and b and initialized them with values 5 and 10.

Inside the swap() function:

  • A copy of a and b is passed to the swap() function.
  • temp stores a (5).
  • a is assigned b (10).
  • b is assigned temp (5).
  • Swapped values (a = 10, b = 5) are printed inside the function.

After the Function Call:

  • Since the function used Call by Value, the original a and b in the main() function remain unchanged.
  • The output still shows a = 5 and b = 10.

Example 2:

Let us take another example to illustrate the Call by Value in C++.

#include <iostream>

using namespace std;


int fun(int a)

{

    a += 18;

    return a;

}


int main()

{

    int a = 2;


    cout << "Before function Calling the value of A: " << a << endl;


    a = fun(a);

    cout << "After function Calling the value of A: " << a << endl;


    return 0;

}

Output:

Before function Calling the value of A: 2

After function Calling the value of A: 20

Uses of Call by Value in C++:

Several uses of Call by Value in C++ are as follows:

  1. It is mainly utilized for passing simple data types, including integers, Boolean, floats, and characters.
  2. It is very useful when we do not wish to alter the actual parameters of the function.
  3. It is also useful when we do not deal with backtracking or recursion.
  4. When we wish to create copies of essential data.
  5. It is useful when we wish to perform calculations without changing the actual parameter values.
  6. It is very important when multiple threads access the shared data.
  7. It prevents one function call from modifying another value.

Advantages of Call by Value:

Several advantages of Call by Value in C++ are as follows:

  1. It is easy to understand and debug because values do not change unexpectedly.
  2. Call by value functions are free to alter the passed data without affecting the actual data.
  3. It is useful in parallel processing when multiple threads work on the same function.
  4. There is no risk of memory leaks or dangling pointers.
  5. Because the function cannot alter the actual data, it aids in preventing unintended changes.
  6. When a function is called, it does not affect the actual data of the actual parameter.

Disadvantages of Call by Value:

Several disadvantages of Call by Value in C++ are as follows:

  1. If the parameter is huge, it takes a lot of time to copy the data.
  2. It does not work effectively with dynamic memory allocation.
  3. Each function call makes a new copy in recursive functions, which consumes more stack memory.
  4. Huge memory space is required while using array, vector, string, etc.
  5. If a function is invoked too many times using Call by Value, new copies are made for each call, resulting in a stack overflow.

Frequently Asked Questions (FAQ’s)

1. What is Call by Value?

Call by Value is a function of passing arguments to a function where copies of the original values are passed. It means that any changes inside the parameter do not affect the original variables.

2. Does Call by Value work with arrays in C++?

No, Arrays are only passed by reference in C++.

3. Does Call by Value work with objects?

Yes, but it is inefficient because it makes a copy of the complete object.

4. Is Call by Value faster than Call by Reference?

No, Call by Value is slower for large data types (structs, classes, arrays) because it makes copies of actual parameters. Call by Value is fast for simple data types (int, char, boolean, float) because they are small in size.


Related Topics

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.