Module 9
Module 9
PROGRAMMING
MODULE 9
FUNCTION IN C++
A function is a group of statements that together perform a specific task. Every C++
program has at least one function, which is main().
Advantage of Function
Code Re-usability
Develop an application in module format.
Easily to debug the program.
Code optimization: No need to write lot of code.
Type of Function
There are two type of function in C++ Language. They are:
Library function or pre-define function.
User defined function.
Library function
Library functions are those which are predefined in C++ compiler. The implementation part
of pre-defined functions is available in library files that are .lib/.obj files. .lib or .obj files are
contained pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.
2
Limitations of Library function
All predefined function contains limited task only that is for what purpose a function is
designed for same purpose it should be used.
As a programmer we do not have any controls on predefined function
In implementation whenever a predefined function is not supporting user requirement
then go for user defined function.
DEFINING A FUNCTION
Defining of function is nothing but gives body to a function, that means write logic inside
function body.
Syntax
return_type function_name(parameter)
{
function body;
}
Return type: A function may return a value. The return_type is the data type of the value
the function returns. Return type parameters and returns statement are optional.
Function name: Function name is the name of function it is decided by programmer or
you.
Parameters: This is a value which is pass in function at the time of calling of function. A
parameter is like a placeholder. It is optional.
Function body: Function body is the collection of statements.
FUNCTION DECLARATIONS
A function declaration is the process of tells the compiler about a function name. The actual
body of the function can be defined separately.
Syntax
return_type function_name(parameter);
CALLING A FUNCTION
When we call any function, control goes to function body and execute entire code. To call
any function, just write name of function and if any parameter is required then pass
parameter.
3
Syntax
function_name();
or
variable=function_name(argument);
Example of Function
#include <iostream>
using namespace std;
void main()
{
clrsct();
sum(); // calling function
}
Output
Sum: 30
4
INLINE FUNCTION IN C++
Inline Function is powerful concept in C++ programming language. If a function is inline, the
compiler places a copy of the code of that function at each point where the function is called
at compile time.
To make any function inline function just preceded that function with inline keyword.
Syntax
inline function_name()
{
//function body
}
Example
#include <iostream>
using namespace std;
int show();
int main()
{
show(); // Call it like a normal function
}
Output
Hello word