Functions in C++

In this tutorial, we will lean about function, its declaration, calls with example.

functions in c++

Functions break large computing tasks into smaller ones, and enable people to build on what others have done instead of starting over from scratch.

Structure of function in C++

//Structure of C++ program
#include <iostream>
using namespace std;
return_type function_name(parameter_list); //function prototype

void main()
{
  ........
  function_name();   //function call
  ........
}

return_type function_name(parameter_list)  //function definition
{
  ........
  function definition
  ........
}

A function is a named sequence of code that performs a specific task. Lets, take example of square root function in c++.  

Example to calculate square root using C++

#include <iostream>
#include <cmath>

using namespace std;

int main () 
{
  double input;
  cout << "Enter a positive integer: ";
  cin >> input;
  double root = sqrt (input); //call sqrt function
  cout << root;
   return 0;
}

Output

Enter a positive integer: 5
2.23607

Here,

#include <cmath>

above line include the scource code of cmath library to above program. sqrt is the function that is include in cmath library.

sqrt (input)

Above expression is the function call. sqrt  function takes input and calculate inside the function and returns the value. Hence without making the code complex we calculated the square root of given number.

Functions without Return Value

It is not necessary that function must return value. A function may perform certain operation without returning any value. For that, function are defined using type void .

Syntax

void function_name(data_type value);

Functions without Arguments

A function also may not take any argument. For example, rand() function return random value bewteen 0 and 32767 without any argumet being passed to it.

Syntax

int rand();