C++ Function Parameters

Function parameters in C++ allow passing data into functions. They can be passed by value, by reference, or using pointers, enabling flexible and reusable code.

1. Pass by Value

In pass-by-value, the function receives a copy of the argument. Changes inside the function do not affect the original variable.

C++
Example: Pass by value
#include <iostream>
using namespace std;

void increment(int a) {
    a = a + 1;
    cout << "Inside function: " << a << endl;
}

int main() {
    int x = 5;
    increment(x);
    cout << "Outside function: " << x << endl;
    return 0;
}

2. Pass by Reference

In pass-by-reference, the function receives the actual variable, so changes inside the function affect the original variable.

C++
Example: Pass by reference
#include <iostream>
using namespace std;

void increment(int &a) {
    a = a + 1;
    cout << "Inside function: " << a << endl;
}

int main() {
    int x = 5;
    increment(x);
    cout << "Outside function: " << x << endl;
    return 0;
}

3. Pass Using Pointers

You can also pass parameters using pointers to modify the original variable.

C++
Example: Pass using pointers
#include <iostream>
using namespace std;

void increment(int *a) {
    *a = *a + 1;
    cout << "Inside function: " << *a << endl;
}

int main() {
    int x = 5;
    increment(&x);
    cout << "Outside function: " << x << endl;
    return 0;
}

4. Common Mistakes

Passing by value when modification is required or forgetting to use & for pass-by-reference are common mistakes. Always choose the correct parameter type.

Conclusion

C++ function parameters allow data to be passed into functions in multiple ways. Choosing the right method—by value, reference, or pointer—ensures correct and efficient program behavior.