Function
parameter in C++ like an ingredient you give to a recipe (the function). The recipe specifies what kind of ingredients it needs (parameter types), and when you cook (call) the recipe, you provide the actual ingredients (arguments). The function then uses these ingredients to perform its task and might give you a tasty result. Parameters help functions customize their actions based on what you give them.
Syntax of a Function Paramters:
ReturnType
functionName
(
ParameterType1
paramName1
,
ParameterType2
paramName2
, ...) {
}
Functions can be categorized into two main types based on parameters, functions
with
parameters and functions
without
parameters.
Functions with Parameters
Functions with parameters receive input values, known as parameters, when they are called. These parameters allow the function to perform operations or computations using the provided values.
#include
<iostream>
void
greetUser
(
std::string
name
) {
std::cout
<<
"Hello, "
<<
name
<<
"!"
<<
std::endl
;
}
int
main
() {
greetUser
(
"John"
);
return
0;
}
In this example, the
greetUser
function takes a single parameter name,
allowing
it to greet the user by name when called.
Functions without Parameters
Functions without parameters do not take any input values when they are called. They are designed to perform a task or provide a result without relying on external values.
#include
<iostream>
void
printMessage
() {
std::cout
<<
"This is a simple message."
<<
std::endl
;
}
int
main
() {
printMessage
();
return
0;
}
In this example, the
printMessage
function does not require any input parameters. It simply prints a
predefined
message when called.