In C++, a function is a set of statements which are executed together when the function is called. Every function has a name, which is used to call the respective function.
C++ has many built-in functions. In order to use them, we have to import the required library using
Calling a Function
In C++, when we define a function, it is not executed automatically. To execute it, we need to “call” the function by specifying its name followed by a pair of parentheses
Function Declaration & Definition
A C++ function has two parts:
The declaration includes the function’s name, return type, and any parameters.
The definition is the actual body of the function which executes when a function is called. The body of a function is typically enclosed in curly braces.
In C++, if we declare the type of a function as
void, it does not return a value. These functions are useful for a set of statements that do not require returning a value.
Return Values in Functions
A function that returns a value must have a
return statement. The data type of the return value also must match the method’s declared return type;
On the other hand, a
void function (one that does not return anything) does not require a
In C++, function parameters are placeholders for values passed to the function. They act as variables inside a function.
In C++, the values passed to a function are known as arguments. They represent the actual input values.
Scope of Code
The scope is the region of code that can access or view a given element:
Function Declarations in Header file
C++ functions typically have two parts: declaration and definition.
Function declarations are generally stored in a header file (.hpp or .h) and function definitions (body of the function that defines how it is implemented) are written in the .cpp file.