In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is:type name ( parameter1, parameter2, ...) { statements }
Where:
– type
is the type of the value returned by the function.
– name
is the identifier by which the function can be called.
– parameters
(as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example:int x
), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from.
– statements
is the function’s body. It is a block of statements surrounded by braces { } that specify what the function actually does.
Let’s have a look at an example:
Mastery 12 by Jose Eduardo Sanchez is licensed under a Creative Commons Attribution 4.0 International License.