Functions IN C++: by Muhammad Atif Bajwa
Functions IN C++: by Muhammad Atif Bajwa
By
Muhammad Atif Bajwa
FUNCTIONS
IN
C++
FUNCTION
A function is a self contained block of codes or sub programs
with a set of statements that perform some specific task or
coherent task when it is called
Basically a job of function is to do something (to perform some
task)
It is something like to hiring a person to do some specific task
like, every six months servicing a bike and hand over to it
C++ program contain at least one function which is main()
Why We Use Functions
Several advantages of modularizing a program into
function
Reduction in code redundancy
Enabling code reuse
Better readability
Information Hiding
Improved debugging and testing
Improved maintainability
Library Functions
System defined function can't be modified, it can only
read and can be used.
These function are supplied with every C++ compiler.
Source of these library function are pre complied and
only object code get used by the user by linking to the
code by linker
Library Functions
Also Called Built-in Functions
They are written in the header files
To use them desired header file must be included
User Defined Functions
User defined functions defined by the user according to
its requirements
Syntax:
Return type name_0f_function (parameters)
User Defined Functions
Function definition
Function call
Function Declaration
Provides the compiler with the description of functions
that will be used later in the program
Its define the function before it been used/called
Function prototypes need to be written at the beginning
of the program, done outside main function
The function prototype must have : A return type
indicating the variable that the function will be return
Function Declaration
Syntax for Function Prototype
return-type function_name (parameters)
Function Prototype Examples
double squared( double number );
void print_report (int report_number );
int get_menu_choice( void):
Function Definition
Function definition tell us what the function will do
Defines the logic of function, done outside main function
Without definition declaration is of no uses
Syntax
Data_type Function_name (Parameters)
{
Body;
}
Function Call
Function call means to activate the function
Means to call the function
By Calling Function it will execute and give output
Function Call must be in the main function
Syntax
function_name();
Example : sum();
How Function Works
Recursion
Any function can be called from any other function, even
a function can call itself, this process is called the
recursion