C++ User-defined Functions

Function in c++ is a unique named block of code to perform certain tasks. All the statements written in the function body are executed when a function is called by its name. 

The control moves to the function body when a programmer calls a function. After that, all the statements inside the function are executed. In the end, the control again moves at the place where the function was called along with possible return values.


 Type of functions:

There are two types of functions.

  • User-defined function:  is a type of function that is written by the programmer.
  • Built-in functions: these are the functions that are pre-written as part of the programming language. 

Note: In this tutorial, we will cover only user-defined functions.


User-defined Function

Here we see how to declare a function.

return_type function_name (parameters)

Return type: is the data type of the value that function is going to return. For example “int” data type is used if the function returns the integer value.

Function_name: it specifies the unique name of the function

Parameters: are the values that pass to the function to perform the required task. These are enclosed by parenthesis and separated by commas.

Function definition

Writing full function including function header and function body is known as a function definition. All the statements are written during the function definition.

Syntax

return_type function_name (parameters)
{
statements;
}

Function Call

A function call is a statement that initiates the working of the function.  We can call the function at any part of the program.

Syntax

funcion_name(parameters);

Example: User-defined Function in C++

//user-defined function in C++
#include <iostream>
using namespace std;

// function declearation
void show() {
    cout << "Hello World!"<<endl;
}
int main() {
// function call
    show();

    return 0;
}

Output

Hello World!