C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Argument passing (with its types) in C++ programming language

Learn: What is argument passing in C++ programming language, how many types of argument passing that we can use in a C++ programming?

Passing information from calling function (Method) to the called function (method) is known as argument passing, by using argument passing, we can share information from one scope to another in C++ programming language.

We can pass arguments into the functions according to requirement. C++ supports three types of argument passing:

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

1) Pass by Value

In case of pass by value, we pass argument to the function at calling position. That does not reflect changes into parent function. Scope of modification is reflected only in called function.

Consider the example:

#include <iostream>
using namespace std;

void fun(int a)
{
	a=20;
}
int main()
{
	int a =10;

	fun(a);

	cout<<"Value of A: "<<a<<endl;
	return 0;
}

Output

Value of A: 10

Here, variable a is passing as call by value in called function fun(), and the value is changing in the function body but when we print the value in main(), it is unchanged.

2) Pass by Reference

In case of pass by reference, we pass argument to the function at calling position. That reflects changes into parent function. Scope of modification is reflected in calling function also.

Consider the example:

#include <iostream>
using namespace std;

void fun(int &b)
{
	b=20;
}

int main()
{
	int a =10;

	fun(a);

	cout<<"Value of A: "<<a<<endl;
	return 0;
}

Output

Value of A: 20

Consider the function definition (or declaration) void fun(int &b), while calling the function fun(), reference of a will be passed in the function body, whatever changes will be made in the function body, will change the original value. Thus, value of a is changed and it is now 20 in main().

3) Pass by Address or pass by Pointer

In case of pass by reference, we pass argument to the function at calling position. That reflects changes into parent function. Scope of modification is reflected in calling function also.

Consider the example:

#include <iostream>
using namespace std;

void fun(int *b)
{
	*b=20;
}

int main()
{
	int a =10;

	fun(&a);
	
	cout<<"Value of A: "<<a<<endl;
	
	return 0;
}

Output

Value of A: 20

Here, while calling the function fun(), we are passing address of a (&a) which will be stored in the pointer b(in function declaration: void fun(int *b)), whatever changed will be made with the b (which holds the address of a) will reflect to the original value of a. Thus, value of a is changed and it is now 20 in main().









COMMENTS