The Wayback Machine - https://web.archive.org/web/20240911210338/https://www.geeksforgeeks.org/parameter-passing-techniques-in-cpp/
Open In App

Parameter Passing Techniques in C++

Last Updated : 28 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, data must be sent to functions when they are called in order to perform operations. This data is called parameters or arguments and there are various parameter passing methods available in C++, each with merits and demerits of its own. In this article, we will discuss various parameter-passing techniques in C++.

Basic Terminologies

  • Function Parameters: These variables, which indicate the data that the function anticipates receiving when called, are specified in the parameter list of a function.
  • Actual Parameters: The expressions or values passed in during a function call. When the function is called, it receives these values as input.
  • The parameters that the function signature declares. They serve as stand-ins for the values that are provided in when the function is called.

Parameter Passing Techniques in C++

There are 3 different methods using which we can pass parameters to a function in C++. These are:

  1. Pass by Value
  2. Pass by Reference
  3. Pass by Pointers

1. Pass by Value

In Pass by Value method, a variable’s actual value is copied and then passed to the function instead of the original variable. As the result, any changes to the parameter inside the function will not affect the variable’s original value outside the function. Althogh it is easy to understand and implement, this method is not so useful for large size of data structures at it involves copying the value.

Example

C++




// C++ program to illustrate the pass by value
#include <iostream>
using namespace std;
  
// function to swap variables
void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
}
int main()
{
    int x = 5;
    int y = 10;
  
    cout << "Before Swapping:\n";
    cout << "x = " << x << ", y = " << y << endl;
  
    // Call the 'swap' function with pass-by-value
    // parameters
    swap(x, y);
  
    // Print the values of 'x' and 'y' after the
    // (ineffective) swap The values remain unchanged
    // because the function works on copies.
    cout << "After Swapping:\n";
    cout << "x = " << x << ", y = " << y << endl;
  
    return 0;
}


Output

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

2. Pass by Reference

In pass-by-reference method, instead of passing the argument itself, we passes the reference of an argument to the function. This allows the function to change the value of the original argument.

Any changes we make to your argument inside your function are reflected in your original argument so we have to be careful while handling data in this method.

Example

C++




// C++ program to illustrate the use of pass by reference
#include <iostream>
using namespace std;
  
// function to swap variables
void swap(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}
  
// driver code
int main()
{
    int x = 5;
    int y = 10;
    cout << "Before swap:\n";
    cout << "x = " << x << ", ";
    cout << "y = " << y << endl;
  
    // Call the 'swap' function with pass-by-reference
    // parameters Values of 'x' and 'y' are modified in the
    // calling code because references are used.
    swap(x, y);
  
    cout << "After swap:\n";
    cout << "x = " << x << ", ";
    cout << "y = " << y << endl;
    return 0;
}


Output

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

3. Pass by Pointer

The pass-by-pointer is very similar to the pass-by-reference method. The only difference is that we pass the raw pointers instead of reference to the function. It means that we pass the address of the argument to the function.

Example

C++




// C++ program to illustrate the pass by pointer method.
#include <iostream>
using namespace std;
  
// function to swap variables
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
  
// driver code
int main()
{
  
    int x = 5;
    int y = 10;
  
    // Print the values of 'x' and 'y' before the swap
    cout << "Before swap:\n";
    cout << "x = " << x << " ,";
    cout << "y = " << y << endl;
  
    // Call the 'swap' function with pass-by-pointer
    // parameters
    // Values of 'x' and 'y' are modified in the calling
    // code because pointers are used.
    swap(&x;, &y;);
  
    // Print the values of 'x' and 'y' after the swap
    cout << "After swap:\n";
    cout << "x = " << x << " ,";
    cout << "y = " << y << endl;
  
    return 0;
}


Output

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


Similar Reads

Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing by Pointer Here, the memory location (address) of
5 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &amp;lt;iostream&amp;gt; #include &amp;lt;vector&amp;gt; using namespace std; class MyClass { vector&amp;lt;int&amp;gt; vec; public: MyClass(vector&amp;lt;int&amp;gt; v) { vec = v; } void print()
2 min read
How to delete an element from the Set by passing its value in C++
Given a Set, the task is to remove the last element from this Set in C++.Examples: Input: set = [10 20 30 70 80 90 100 40 50 60], valueOfElementToBeDeleted = 100 Output: 10 20 30 40 50 60 70 80 90 Input: set = [1 2 3 4 5], valueOfElementToBeDeleted = 3 Output: 1 2 4 5 Sets are a type of associative container in which each element has to be unique b
6 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Passing Map as Reference in C++ STL
Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms of computation and memory resources. When we pass
3 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
Passing Vector to a Function in C++
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By valuePass By Reference When a vector is passed to a function, a copy of the vector is created. This new copy of the vector is then used in the function and thus, any changes made to the vector in the function do not affe
3 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
How to print size of array parameter in C++?
How to compute the size of an array CPP? C/C++ Code // A C++ program to show that it is wrong to  // compute size of an array parameter in a function #include &lt;iostream&gt; using namespace std; void findSize(int arr[]) { cout &lt;&lt; sizeof(arr) &lt;&lt; endl; } int main() { int a[10]; cout &lt;&lt; sizeof(a) &lt;&lt; &quot; &quot;; findSize(a)
3 min read
Optimization Techniques | Set 2 (swapping)
How to swap two variables? The question may look silly, neither geeky. See the following piece of code to swap two integers (XOR swapping), void myswap(int *x, int *y) { if (x != y) { *x^=*y^=*x^=*y; } } At first glance, we may think nothing wrong with the code. However, when prompted for reason behind opting for XOR swap logic, the person was clue
1 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
GCD of Two Numbers in C++
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that exactly divides both numbers. In this article, we will learn to write a C++ program to find the GCD of two numbers. Recommended PracticeLCM And GCDTry It!1. GCD Using Simple MethodThe idea is to find the minimum of the two numbers and then find th
4 min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :