C++ Functions


Go to main Page

Functions in C++

In this tutorial we are going to learn about C++ Functions with examples.

Defination: A function is a block of code that runs when it is called.

We can pass parameters in a function.

Functions are used to perform specific tasks.

We can reuse the code by functions.

Write code once and reuse it much time just by calling.

Suppose we need to draw a circle five times. We just need to code only one time. And then we can use it by calling it five-time.

Types of Functions

There are two types of functions:

  1. Pre-defined functions
  2. User defined functions

Pre-defined functions

C++ programming has some pre-defined funtions such as main()

User-defined functions

C++ programming allow its user to create its own function to perform specific tasks.

To create a function write function name which is followed by ().

Syntax

returnType functionName (parameter1, parameter2,...) {
    // function body   
}

Example


void Hello() {
    cout << "Hyy Programmers";
}

Explaination

Calling a Function

In the above example, we declared the function and now we are going to call a function.

To call a function write function name followed by parentheses and a semicolon;

Example

int main()
    {
        //body
        Hello();
    }

Diagram
Example :Print text by using functions.

#include <iostream>
using namespace std;
void Hello() {
    cout << "Hello Programmers!";
}

int main() {
    Hello();

    return 0;
}

Output


Hello Programmers!


Paramterized Functions

Information can be passed to functions as a parameter. Parameters act as variables inside the function.

Example


void printNum(int num) {
    cout << num;
}

Example : Function with parameters


#include <iostream>
using namespace std;

void displayNum(int n1, float n2) {
    cout << "The int number is " << n1;
    cout << "The double number is " << n2;
}

int main() {
     
     int num1 = 5;
     double num2 = 5.5;
    displayNum(num1, num2);

    return 0;
}

Output

The int number is 5
The double number is 5.5