Functions in C++
A function is a group of statements that is executed when it is called from some point of the program
Syntax for defining a Function
datatype functionname ( parameter1, parameter2, ...)
{
Statements;
}
Where:
- datatype is the type of the value returned by the function.
- name is the identifier by which the function can be called.
- parameters (as many as needed): The purpose of parameters is to allow passing arguments to the function from the location where it is called from.
- statements is the function's body. It is a block of statements surrounded by braces { } that specify what the function actually does.
Advantages of using functions
- Dividing a large program into small functions
- It is possible to reduce the size of a program by calling and using them at different places in the program
- When the function is called, control is transferred to the first statement in the function body.
- Debugging will be easy
- Easy to read
The main() function
main() function is the starting point for the execution of a program
void main()
{
}
Steps to Use functions in c++
- Declare a function (Function Prototyping)
- Define a function
- Call the function
Step 1: Declare the function (Function prototyping)
Function prototyping is a declaration statement and describes the function interface to the compiler by giving details such as number of parameters, data type of parameters/arguments and the type of return values
Example
float add(int x, int y);
Step 2: Define a function
Statements can be defined in this step using the following syntax
Syntax
Datatype function_name(parameter_list)
{
Statements;
}
Example
float add(int x,int y)
{
Statements;
}
Step 3: Calling the function
Statements can be defined in this step using the following syntax
If no return type -> add(10,20);
If return type-> float k=add(10,20);
TYPES OF PASSING PARAMETERS IN FUNCTIONS
- Function without parameters and without return type
- Function with parameters and without return type
- Function without parameters and with return type
- Function with parameters and with return type
Example 1:
In this example, the function is used to add two values, without parameters and no return type
# include <iostream.h>
#include <conio.h>
void add(); //declaration
void add() //define a function
{
int a,b,c;
a=10;
b=20;
c=a+b;
cout<<“Answer=“<<c;
}
void main()
{
add(); //calling
}
Comments