Introduction :
Functions in C++
A block of code which comes into execution when it is called is a function.
We can pass data to the function which are called as parameters.
Functions are known for performing certain actions, and they play a significant role in code reusanility: You can define the code once, and then use it many times.
Creating a functions in c++
Syntax:
Example Explanation:
- rishFunc() is the name of the function
- void specific’s that the function does not have a return value.
- inside the function, we are supposed to add code that defines what the function should do
Calling a Function:
Functions are not executed immediately after being declared. They are actually saved for later use, and when they will be called they will get executed.
We have to write the function’s name followed by two parentheses () and a semicolon to call a function;
Following is an example, rishFunc () is used to print any text , when it is called:
For Example:
Outputs: “Hey There! I’m Rishu”
Declaration and Definition of a function:
A functions in c++ generally consists of two parts:
- Declaration: It is supposed to consist the return type, the name of the function, and parameters (if present)
- Definition: It is considered to be the body of the function (the desired code to be executed)
Note: , An error will occur if a user-defined function, such as rishFunc () is declared after the main() function
Example:
However, it can be possible for someone to separate the declaration and the definition of the function – for the sake of code optimization.
One can often see C++ programs that generally have function declarations above main(), and function definition is generally found below main(). This is supposed to make the code better organized and easier to read:
For example: