Function Parameters in C++
In C++, parameters are used to pass information into functions. Think of them as the inputs that functions use to perform their tasks. When you call a function, you can pass values (called arguments), and those values are caught by the parameters in the function definition.
📥 Basic Parameter Example
Let’s create a function that takes two parameters and prints their sum:
#include <iostream> using namespace std; void printSum(int a, int b) { cout << "Sum is: " << (a + b) << endl; } int main() { printSum(10, 20); // Passing arguments return 0; }
🔁 Call by Value
When you pass arguments by value, the function gets a copy of the variables. Changes made inside the function do not affect the original variables.
#include <iostream> using namespace std; void changeValue(int x) { x = 100; } int main() { int num = 50; changeValue(num); cout << "Original num: " << num << endl; return 0; }
🔗 Call by Reference
With reference parameters, the function receives the actual variables. Changes made inside the function affect the original values.
#include <iostream> using namespace std; void changeValue(int &x) { x = 100; } int main() { int num = 50; changeValue(num); cout << "Changed num: " << num << endl; return 0; }
✨ Default Parameters
You can also give default values to parameters. If no argument is passed, the default is used!
#include <iostream> using namespace std; void greet(string name = "Guest") { cout << "Hello, " << name << "!" << endl; } int main() { greet(); // Uses default greet("Charlie"); // Uses provided value return 0; }
✅ Summary
- Parameters are variables listed in a function’s definition.
- You pass arguments when you call the function.
- Call by value: function works with a copy.
- Call by reference: function works with the actual variable.
- Default parameters provide fallback values.
Mastering parameters makes your functions powerful and flexible. 🚀