×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to demonstrate methods of passing arguments in function

Learn about the various methods of passing arguments in C++ functions with an example.
[Last updated : March 01, 2023]

Different methods of argument passing in C++ Functions

There are three types of argument passing in C++ function, they are:

  1. Pass by value
  2. Pass by reference
  3. Pass by address

In this program we will learn different methods of passing arguments in functions in c++ programming language.

Pass by value, Pass by reference, Pass by address

Methods of passing arguments in function example in C++

/*C++ program to demonstrate methods of passing arguments in function.
  Pass by value, Pass by reference, Pass by address.
*/
 
#include  <iostream>
using namespace std;
 
void swapByValue( int a , int b  );
void swapByRef  ( int &a, int &b );
void swapByAdr  ( int *a, int *b );
 
int main()
{
    int x = 10;
    int y = 20;
 
    cout << endl;
    cout << "Value before Swapping x:" << x << " y:" << y << endl;
    swapByValue( x , y  ); /*In call by value swapping does not reflect in calling function*/
    cout << "Value After  Swapping x:" << x << " y:" << y << endl << endl; 
 
    cout << "Value before Swapping x:" << x << " y:" << y << endl;
    swapByRef( x , y  );  /*Swapping reflect but reference does not take space in memory*/
    cout << "Value After  Swapping x:" << x << " y:" << y << endl << endl; 
 
    x = 50;
    y = 100;
 
    cout << "Value before Swapping x:" << x << " y:" << y << endl;
    swapByAdr( &x , &y  ); /*Swapping reflect but pointer takes space in memory*/
    cout << "Value After  Swapping x:" << x << " y:" << y << endl << endl;  
 
    return 0;
}
 
void swapByValue( int a , int b  )
{
    int c;
     
    c = a;
    a = b;
    b = c;
}
 
void swapByRef( int &a , int &b  )
{
    int c;
     
    c = a;
    a = b;
    b = c;
}
 
void swapByAdr( int *a , int *b  )
{
    int c;
     
     c = *a;
    *a = *b;
    *b =  c;
}

Output

Value before Swapping x:10 y:20
Value After  Swapping x:10 y:20

Value before Swapping x:10 y:20
Value After  Swapping x:20 y:10

Value before Swapping x:50 y:100
Value After  Swapping x:100 y:50

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.