C++ Passing arguments to functions
In C++, there are three different ways to send parameters to functions: by value, by reference, and by pointer.
Making a copy of the argument and passing it to the function by value is known as passing by value. A reference or alias of the original variable is passed to the function when something is passed by reference. Moreover, sending by pointer involves giving the function the original variable’s memory address.
Passing by value:
Syntax:
return_type function_name(data_type parameter1, data_type parameter2, ...) {
// Function body
}
Example:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int x = 5, y = 10;
int sum = add(x, y);
cout << "The sum is: " << sum << endl;
return 0;
}
In the above example, add()
function takes two arguments a
and b
by value, and returns their sum.
Passing by reference:
Syntax:
return_type function_name(data_type& parameter1, data_type& parameter2, ...) {
// Function body
}
Example:
#include <iostream>
using namespace std;
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
In the above example, swap() function takes two arguments a and b by reference, and swaps their values.
Passing by pointer:
Syntax:
return_type function_name(data_type* parameter1, data_type* parameter2, ...) {
// Function body
}
Example:
#include <iostream>
using namespace std;
void increment(int* p) {
(*p)++;
}
int main() {
int x = 5;
increment(&x);
cout << "The incremented value of x is: " << x << endl;
return 0;
}
In the above example, increment() function takes a pointer argument p, and increments the value it points to by 1.