C++ Function Basics

Function In C++

A function is a group of code or code block, which performs a specific task. It is also called as a method or a sub program .

The main advantage of the function is that it reduces complexity and size of the program. This is possible because a function can be called or used any number of times in a program.

  • Standard Library Function: These functions are already defined by relevant header file and can be used directly by including them as headers.

  • User Defined Function: A code block that is created by the user is called a User-defined function. In C++, a user can define his own function with its own unique functionalities.

Unlike C, C++ has many features in functions like Function overloading, default arguments, inline functions, friend functions, and virtual functions

Understanding Functions In C++

In C++, Functions are the main building blocks of the program. When a function is called, the program control is passed to the body of the function. Function executes each and every statement in the function body and program control returns when return statement or closing braces(}) is reached.

General Syntax of Functions In C++

#include<iostream>

using namespace std;

void myFunction(); // Function Declaration

int main() {
   ....
   myFunction(); // Function Call
   ....
}

void myFunction() // Function Definition
{
   // Body of the Function
   ....
   ....
}

While running the program, when the compiler reaches the myFunction() function call statement, it passes the control to the definition of the myFunction() and executes the body of myFunction().After the body is completed, program control returns back to the main function and the statements following the function call are executed from the main function.

The below example helps you for the better understanding of this concept.

Simple First Function Example Program In C++

#include<iostream>

using namespace std;

void myFunction(); // Function Declaration

int main() {
   cout << "\nAbove - Function Call";

   myFunction(); // Function Call

   cout << "\nBelow - Function Call";
}

void myFunction() // Function Definition
{
   cout << "\nMy First Function In C++";
}

Sample Output

Above - Function Call
My First Function In C++
Below - Function Call