- Function is defined as a named group of statements.
- A function can be called from any point in a program.
- If a problem can be divided into small modules, then each module can be represented as a function.
- There are two type of functions in C++. They are
- Library function
- User defined function.
- These are functions which are not required to be written by the programmer.
- But these are available in separate files and the programmer has to include it in the appropriate places.
- ββcin >>, cout<< etc.
User Defined Function
A user defined function or simply functions have to be written by the programmer to carry out some specific well defined task.
All C++ programs consist of one or more functions.
Out of this one function should contain main.
This function shows from where the program execution begins.
|Note: Library function is also called as Built in function|
- A function should be defined before it is used.
- A function has two parts. They are
- Function header
- Statement body
The general format of defining a function is given below
Function type function name (list of arguments)
Local variable declaration;
return (expression); }
Function type - represents the data type of the value returned by the function
Function name - valid C++ variable name
List of arguments- formal argument
Local variable - declaration of variables in the statement body
Return - keyword to return the value of the function to other functions.
|Rules for defining a function:|
- Function header should not terminate with semicolon
- List of arguments and argument declaration are optional
- if the function has no list of arguments an empty parenthesis is a must.
- The expression in the return statement is optional
- The parentheses around the expression in the return statement is optional
int abc(int I, int j)
k = I + j;
Declaring Function Type
The function type in the function header is optional.
If there is no function type in the function header the return statement by default returns a integer value.
But with the help of the option function type in the function header we can declare the type of the value returned by the function.
Type function_ name (parameter list);
Use of void Statement
void statement does not return any value.
It can be used to declare any function.
It specifies an empty set of values and it is used as the return type for function that does not return a value.
Thus a function that does not return a value is declared as follows
The general format is
void function_name(parameter list);