All Topics

Functions



A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.
Creating Functions
C++ provides some pre-defined functions, such as main(), which is used to execute code.
But you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed by parentheses ().

Function Declaration and Definition
A C++ function consist of two parts:
Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)



Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will occur.

However, it is possible to separate the declaration and the definition of the function - for code optimization.
You will often see C++ programs that have function declaration above main(), and function definition below main().
This will make the code better organized and easier to read

Call a Function

Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are called. To call a function, write the function's name followed by two parentheses () and a semicolon ; In the following example, myFunction() is used to print a text (the action), when it is called.



A function can be called multiple times.


Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the function.
Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a comma



When a parameter is passed to the function, it is called an argument.
So, from the example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters can also be passed through functions.
When no argument is passed, we can also declare default parameters using '=' operator.



Return Values:-

The void keyword, used in the previous examples, indicates that the function should not return a value.
If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function

Pass by Reference:- (passing the reference of variables)



Note: Multiple functions can have the same name as long as the number and/or type of parameters are different. (Function Overloading)



Hello