Purpose of a Function Prototype in C/C++



In this article, we will explore the purpose of using function prototypes in C or C++.

What are Function Prototypes?

The function prototypes tell the compiler about the number of arguments and the required data types of function parameters; they also tell the compiler about the return type of the function. With this information, the compiler cross-checks the function signatures before calling it.

If the function prototypes are not mentioned, then the program may be compiled with some warnings and sometimes generate some strange output.

Purpose of a Function Prototype

When a function is called before it is defined, and it's function body (code section) is written later in the code. This can lead to problems since the compiler does not recognize the function or its signature. In such cases, function prototypes are required. However, if the function is defined before in the code, then prototypes are not required.

C Example of Function Prototypes

In this example, we will demonstrate the working of the function prototype in C:

#include<stdio.h>
// Function prototype
void function(int x);

int main() {
   function(50);
   return 0;
}

// Function definition
void function(int x) {
   printf("The value of x is: %d", x);
}

Following is the output of the song:

The value of x is: 50

If a Function Is Not Declared Before Its Call

If a function is not declared (i.e., function's prototype is not there) before its call, the compiler may return error. Let us understand through the following example:

#include<stdio.h>
int main() {
   function(50);
   return 0;
}
// Function definition
void function(int x) {
   printf("The value of x is: %d", x);
}

We will get the following error:

error: implicit declaration of function 'function' [-Wimplicit-function-declaration]
warning: conflicting types for 'function'; have 'void(int)'

C++ Example of Function Prototypes

In this example, we will demonstrate the working of the function prototype in C++:

#include<iostream>
using namespace std;

//Function Prototype
void function(int a, int b);

int main() {
   function(50, 40);
   return 0;
}
// Function definition
void function(int a, int b) {
   cout<<"The Sum: "<<a+b<<endl;
}

Following is the output:

The Sum: 90
Updated on: 2025-06-12T14:58:45+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements