Functions in C++
Functions in C++
Functions in C++ is a subprogram to which any data can be send but which returns only one value. It avoids rewriting the same code. It is a block of code that perform same operation. It permit to structure the programs in segments of code to perform individual tasks and it is a group of statement having a certain name which can be called later in same program.
With the help of function, program become more readable and understandable .
Function is made by :
-
- Function Definition in C++
- Function Declaration in C++
- Calling a Function
Function Definition in C++
A defining a function specifies the body of the function or provide actual body of function. Defining of a function it should be done before calling it.
Syntax of Function definition
return_type function_name( parameter list ) { body of the function }
Example of a function definition in C++
int sum(int a, int b) { int sum; sum = a+b; return sum; }
Function Declaration in C++
A function declaration used to tell the compiler about a function name and the way of call the function. The declaration should be done before calling it.
Syntax of function declaration
return_type function_name( parameter list );
Example of function declaration
int max(int num1, int num2);
Calling a Function
Whenever a program called the main function, it control the transferred to called function. And this callled function perforn te defining task after that when return statement will be executed it return program control back to main program.
Program of function in C++
#include <iostream> using namespace std; // function prototype int sum(int, int); int main() { int addition; // calling the function and storing // the returned value in sum addition = sum(100, 78); cout << "100 + 50 = " << addition << endl; return 0; } // function definition int sum(int a, int b) { return (a + b); }
Output
100 + 50 = 158
Types of Functions in C++
There are two types of functions in they are follows