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?
What is Argument passing in C++?
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:
- Pass by Value
- Pass by Reference
- Pass by Address
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.
Example of Pass by Value
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.
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.
Example of Pass by Reference
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().
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.
Example of Pass by Address or Pass by Pointer
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().