Functions in C++

Written by

Vaaruni Agarwal

Functions are a vital part of the C++ language. Just as in real life, the functions in C++ are used to perform a particular task.  

Every C++ program begins execution with a main function. It is the starting point of a C++ program. 

Apart from the functions already defined by the C++ standard libraries, a programmer can create his own functions as per the need of the program.

A function can be declared as follows:

[return type] [name_of_function] ([data type] [arg1], [data type] [arg2]...)
{
  // Body of the function
  // This is where you write the code that the function will execute when it is called

  return [statement]; // The return statement specifies the value that the function should return when it is finished executing
}

return type

Here, return type specifies the value that a function may or may not return depending upon the data type. Possible values are:

  • int
  • void
  • float
  • double
  • char and so on

name\_of\_function

The function name, which is an identifier, the rules for giving the name to a function is the same as that of a variable. 

(data type args1, data type args2….)

Here, args stands for arguments. These are the values that a function accepts from the calling function or statement. The data type specifies the type of the arguments.

After that the body of the function begins within the curly braces. All the programming statements must be included inside these curly braces only.

return statement

The last statement, the return statement, specifies what value will the function return to the calling program. This value is determined by the return type of the function.

In case of void, the function does not return any value.

For Example:

#include <iostream.h>

void check_prime(int n); //function declaration

int main()
{
    int number;
    cout<<"Enter any number: ";
    cin>>number;
    check_prime(number); //function calling
    return 0;
}

void check_prime(int n) //function definition
{
    int count = 0;
    for(int i = 2; i < n; i++)
    {
        if(n % i == 0)
        {
            count++;
        }
    }
    if(count == 0)
    {
        cout<<"\nPrime Number";
    }
    else
    {
        cout<<"\nNot prime";
    }
}

Output:

Enter any number

13

Prime Number
Functions in C++