Function parameters let you send information into a function so it can use that information to do its job.
0
0
Function parameters in C++
Introduction
When you want a function to work with different values each time you call it.
When you want to reuse the same function for many tasks by giving it different inputs.
When you want to organize your code by breaking it into smaller parts that need some data to work.
When you want to avoid repeating code by passing values instead of writing similar functions.
When you want to make your program easier to read and understand by naming the inputs clearly.
Syntax
C++
return_type function_name(parameter_type1 parameter_name1, parameter_type2 parameter_name2, ... ) {
// function body
}Parameters are listed inside the parentheses after the function name.
Each parameter has a type and a name, separated by a space.
Examples
A function with one parameter called
name of type std::string.C++
void greet(std::string name) { std::cout << "Hello, " << name << "!" << std::endl; }
A function with two parameters that adds two numbers and returns the result.
C++
int add(int a, int b) { return a + b; }
A function with a default parameter value. If no argument is given, it uses 10.
C++
void printNumber(int number = 10) { std::cout << number << std::endl; }
Sample Program
This program shows two functions with parameters. printSum adds two numbers and prints the result. greet says hello to the given name.
C++
#include <iostream> #include <string> // Function that takes two numbers and prints their sum void printSum(int x, int y) { std::cout << "Sum: " << x + y << std::endl; } // Function that greets a person by name void greet(std::string name) { std::cout << "Hello, " << name << "!" << std::endl; } int main() { printSum(5, 7); // Calls printSum with 5 and 7 greet("Alice"); // Calls greet with "Alice" return 0; }
OutputSuccess
Important Notes
Parameters are like placeholders for values you give when calling the function.
You can have as many parameters as you need, separated by commas.
Parameters help make functions flexible and reusable.
Summary
Function parameters let you send data into functions to work with.
They are listed inside parentheses after the function name with a type and a name.
Using parameters makes your code more flexible and easier to reuse.