A function is a block of code that performs a specific task. In C++, we can divide a large program into the basic building blocks known as function.
A function can be called multiple times to provide reusability and modularity to the C++ program.
Reusability is the main achievement of C++ functions. By using functions, we can avoid rewriting same logic/code again and again in a program.
There are two types of functions in C programming:
• User-defined functions: are the
functions which are created by the C++ programmer. It reduces the complexity of
a big program and optimizes the code.
A function will
have three aspects
1. Function Declaration / function prototype
2. Function Call
3. Function
Definition.
1. Function Declaration / function prototype:
A function must be declared in a C++ program to tell the compiler about the function name, function parameters, and return type.
A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body.
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2, ...);
Ex:
void sum(int x, int y);
The function prototype is not needed if the user-defined function is defined before the main() function.
2. Function call:
Function can be called from anywhere in the program. Control of the program is transferred to the user-defined function by calling it.
Syntax of
function call
functionName(argument1, argument2, ...);
Ex:
sum(a,b);
3. Function definition:
Function definition contains the block of code to perform a specific task. When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.
Syntax of function definition
returnType functionName(type1 argument1, type2
argument2, ...)
{
//body of the function
}
Ex:
void sum(int x, int y)
{
int sum=x+y;
cout<<“
sum is”<< sum;
}
Different aspects of function calling
There are four
different aspects of function calls:
•
function
without arguments and without return value
Ex: void sum( );
•
function
without arguments and with return value
Ex: int sum( );
•
function
with arguments and without return value
void sum(int a,int b);
•
function
with arguments and with return value
int sum(int a,int b);
No comments:
Post a Comment