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. 

cpp user-defined functions

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.

  • C++ User-defined function: a type of function that is written by the programmer.
  • C++ 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.


C++ User-defined Functions

Here we see how to declare a function.

return_type function_name (parameters)

Return type: is the data type of the value that the 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: C++ User-defined Functions

//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!

Recommended Articles

C++ Execution Environment

C++ program’s basic structure

Scroll to Top