C++ Function Parameters

πŸ”§ C++ Function Parameters

Function parameters are variables that receive values when a function is called.
They allow functions to work with different inputs and make code reusable and flexible.


πŸ”Ή 1. Parameters vs Arguments

int add(int a, int b) { // parameters
return a + b;
}

add(5, 10); // arguments

  • Parameters β†’ variables in function definition

  • Arguments β†’ actual values passed to the function


πŸ”Ή 2. Function with Parameters (Basic)

void greet(string name) {
cout << "Hello " << name;
}

greet("Sanjit");


πŸ”Ή 3. Multiple Parameters

int multiply(int a, int b, int c) {
return a * b * c;
}

cout << multiply(2, 3, 4);


πŸ”Ή 4. Call by Value (Default)

A copy of the argument is passed.
Original value is not changed.

void change(int x) {
x = 50;
}

int a = 10;
change(a);

cout << a; // 10


πŸ”Ή 5. Call by Reference (Using &)

The function works on the original variable.

void change(int &x) {
x = 50;
}

int a = 10;
change(a);

cout << a; // 50


πŸ”Ή 6. Call by Pointer

Address is passed to the function.

void change(int *x) {
*x = 100;
}

int a = 10;
change(&a);

cout << a; // 100


πŸ”Ή 7. Default Parameters

Default value is used if no argument is passed.

int add(int a, int b = 10) {
return a + b;
}

cout << add(5); // 15
cout << add(5, 20); // 25

⚠️ Default parameters must be at the end.


πŸ”Ή 8. Array as Function Parameter

void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}

Call:

int a[] = {1, 2, 3};
printArray(a, 3);

πŸ”Ή 9. Structure as Parameter

struct Student {
int id;
string name;
};

void show(Student s) {
cout << s.name;
}


πŸ”Ή 10. const Parameters (Read-Only)

void show(const int &x) {
cout << x;
}

βœ” Prevents modification
βœ” Improves safety and performance


πŸ”Ή 11. Function Overloading with Parameters

int add(int a, int b);
double add(double a, double b);

Same function name, different parameter types.


❌ Common Mistakes

void func(int a = 5, int b); // ❌ invalid

βœ” Correct:

void func(int a, int b = 5);

πŸ“Œ Summary

  • Parameters allow functions to accept input

  • Call by value β†’ copy

  • Call by reference β†’ original value

  • Pointers allow address-based modification

  • Default parameters make functions flexible

  • Use const & for safety and efficiency

You may also like...