Function Prototype in C++ with examples

In this tutorial, we are going to learn about the function prototypes in C++.

What is function prototyping?

A function prototype is basically a declaration of the function that tells the program about the type of the value which is to be returned by the function. It also tells about the number and type of arguments of the function.
Function prototyping is one of the very useful features in C++ as it enables the compiler to perform more powerful checking.

The prototype declaration looks similar to the function definition except for the fact that it has nobody. The prototype terminates in a semicolon which is different while defining the full function definition.

Syntax of function prototype:

return_type function_name( datatype_1, dataype_2, ....)

The function prototype consists of the function name, arguments list, and return type.

Calling function before declaration using function prototyping

In C++ generally function declaration is done before calling the function. But in case, if we want to define a function after the function call, we have to use function prototyping in order to do so.

#include<iostream>
using namespace std;

// function prototype
void multiply(int, int);

int main() {
    // calling the function before declaration.
    multiply(10, 20);
    return 0;
}

// defining function
void multiply(int x, int y) {
    cout << (x * y);
}

Output:

200

In the above code, the function prototype is :

void multiply( int, int);

In the above example, the compiler is being provided with the information related to the function name and its arguments, so we are able to call the function before its declaration all credit to the function prototyping feature in C++.

Consider another example of a function with void return type using function prototyping.

#include<iostream>
using namespace std;

// Function prototype

void func_prototype();//using function with void return type 

int main(){
    func_prototype();
    return 0;
}

void func_prototype(){
    cout<<"Welcome to Codespeedy";
}

Output:

Welcome to Codespeedy

In the above code, the function has a void return type so it does not return anything. We have done prototyping of the function, then called the function, and finally declared it and thus we are getting an output without any error.

Thus, in this article, we have learned function prototyping in C++.

Leave a Reply

Your email address will not be published.