In C++, a function prototype is a declaration of the function that informs the program about the number and type of parameters, as well as the type of value the function will return. One incredibly helpful aspect of C++ functions is function prototyping. A function prototype provides information, such as the number, type of parameters, and type of return values, to explain the function interface to the compiler.
In C++ , a function prototype is a declaration that tells the compiler the function's name, return type, and the number and types of its parameters. It helps ensure that function calls are made correctly before the function is defined.
Syntax
It has the following syntax:
return_type function_name(parameter_type1 parameter_name1, parameter_type2 parameter_name2, ...);
In this syntax,
- return_type: It represents the data type of value that will return (such as int, void, double, etc.)
- function_name: It represents the name that is used to identify and call the function.
- parameter_type: It represents the types of parameters the function expects.
For Instance
Let's look at the prototype for the following function:
int add ( int a1 , int a2 ) ;
here,
- return type: int
- name of the function: add
- argument list: (int a1, int a2)
Since a semicolon follows every function prototype, there will eventually be; just like in the previous function prototype.
Note: While a function definition cannot omit the parameter names, a function declaration can.
Type of Return Values of Function Prototypes in C++
In C++, the return type of a function specifies the type of data sent back to the calling program. If the return type is void, the function does not return any values. It is generally used for operations that do tasks such as publishing output or altering external data without reporting the results.
1) Void Return Type
A void return type in C++ implies that a function completes a task but does not return a value. It is ideal for operations, such as displaying output, logging data, or updating a user interface that does not require the caller to receive any results.
Syntax
It has the following syntax.
void function_name(parameter_list);
C++ Example for Void Return Type
Let's take an example to illustrate the void return type function prototype in C++.
Example
#include <iostream>
#include <string>
void Display(const std::string& companyName)
{
std::cout << "Hello! This is " << companyName << std::endl;
}
int main() //Main Function
{
Display("Cpp Tutorial Company");
return 0;
}
Output:
Hello! This is Cpp Tutorial Company
Explanation:
The code declares a Display function with a void return type that prints an invoice message with the provided company name. The function is invoked in main with the argument "Cpp Tutorial Company", and the output is "Hello! This is Cpp Tutorial Company".
2) Integral return type:
In C++, integral return types (such as int, char, bool, and long) are used when a function must return a complete number, character code, or logical value. These are appropriate for calculation, evaluation, or count-based operations.
Syntax
It has the following syntax.
int add(int x, int y)
C++ Internal Return Type Example
Let's take an example to illustrate the integral return type function prototype in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int addItems(int p1, int p2)
{
return p1 + p2;
}
char Grade(int marks)
{
if (marks >= 90)
return 'A';
else if (marks >= 80)
return 'B';
else if (marks >= 70)
return 'C';
else return 'F';
}
bool Even(int num)
{
return (num % 2 == 0);
}
long factorial(int n)
{
long ans = 1;
for (int q = 2; q <= n; ++q)
{
ans *= q;
}
return ans;
}
int main() //Main Function
{
int totalPrice = addItems(150,350);
cout << "The total price is: " << totalPrice << endl;
char g = Grade(85);
cout << "The Grade achieved is: " << g << endl;
int number = 17;
if (Even(number))
{
cout << number << " is an even number." << endl;
}
else
{
cout << number << " is an odd number." << endl;
}
int num_ber = 6;
long fact_ans = factorial(num_ber);
cout << "Factorial of " << num_ber << " is: " << fact_ans << endl;
return 0;
}
Output:
The total price is: 500
The Grade achieved is: B
17 is an odd number.
Factorial of 6 is: 720
Explanation
In this example, we demonstrate the use of several integral return types by adding, assigning grades, checking evenness, and computing factorials. In the main function, it adds two prices, determines a grade based on marks, determines whether a number is even or odd, and computes the factorial of a number, displays all results.
3) Floating-Point Return Types
When a function must return values that include fractions or decimal points, it uses floating-point return types such as float or double. These are necessary for representing real numbers when precision is essential in scientific calculations, measurements, or financial data.
Syntax
It has the following syntax.
return_type function_name(parameters_list);
C++ Floating-Point Return Types Example
Let's take an example to illustrate the floating point return type function prototype in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
double divide(double p, double q)
{
if (q != 0.0)
{
return p / q;
}
else
{
cerr << "Division by zero error." << endl;
return 0.0;
}
}
int main() //Main Function
{
double ans = divide(20.0, 4.0);
cout << "The result of division is: " << ans << endl;
return 0;
}
Output:
The result of division is: 5
Explanation
In this example, we define a divide function that safely divides two double values, handling division by zero with an error and returning 0.0. In the main function, it runs divide(20.0, 4.0) function, computes the result, which is 5, and prints it to the console.
4) User-Defined Object Return Types:
C++ allows us to define custom classes and return objects from them. This method encapsulates data and behaviour in a way that makes it possible to write reusable, organized code. Returning objects from functions is common when we need to build and pass back an instance of a class so that the caller can interact with it directly.
Syntax
It has the following syntax.
return_type function_name(parameters_list);
C++ User-Defined Object Return Types Example
Let's take an example to illustrate the User-Defined Object return type function prototype in C++.
Example
#include <iostream>
#include <string>
using namespace std; //using standard namespace
class Book
{
public:
string tit_le;
string aut_hor;
Book(const string& tit_le, const string& aut_hor)
: tit_le(tit_le), aut_hor(aut_hor) {}
};
Book creatingbook(const string& tit_le, const string& aut_hor)
{
return Book(tit_le, aut_hor);
}
int main() //Main Function
{
Book mybook = creatingbook("1984", "George Orwell");
cout << "Book Title: " << mybook.tit_le <<endl;
cout << "Book Author: " << mybook.aut_hor <<endl;
return 0;
}
Output:
Book Title: 1984
Book Author: George Orwell
Scope of Function Prototypes in C++
In C++, the scope of a function prototype specifies where the function can be invoked and utilized in the program. A function prototype declares the function's name to the compiler, allowing it to be called before its actual definition.
We can categorize the scope of function prototype into two types:
- Global Scope
- Local Scope
Let us now discuss these types with the help of some examples.
1) Global Scope
When we declared a function prototype in the global scope, it becomes accessible anywhere in the program. It offers greater flexibility in code organization, particularly in large programs where function definitions may occur after their calls.
C++ Global Scope Example
Let's take an example to demonstrate the Global Scope of Function Prototypes in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int sum(int x, int y);
int main() //Main function
{
int ans = sum(15, 8);
cout << "The addition of two numbers are: " << ans << endl; //prints the output
return 0;
}
int sum(int x, int y)
{
return x + y; // perform addition operation
}
Output:
The addition of two numbers are: 23
Explanation
In this example, we define a function sum that adds two integers. In the main function, it calls sum(15, 8), and then stores the result in ans. Finally, it prints the output.
2) Local Scope
In C++ local scope, a function prototype is declared inside single function scope, and it can only be accessible in that function. This function can only be invoked within the function where it is declared.
C++ Local Scope Example
Let us take an example to demonstrate the Local Scope of Function Prototypes in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //Main function
{
int subtract(int x, int y);
int ans = subtract(18, 5);
cout << "The difference between of two numbers are: " << ans << endl; //prints he result
return 0;
}
int subtract(int x, int y)
{
return x - y; //Perform Subtraction Operation
}
Output:
The difference between two numbers are: 13
Explanation
In this example, we define a function subtract that calculates the difference between two integers. In the main function, it calls the subtract(18, 5) function, and then stores the result in ans. Finally, it prints the output.
Advantages of Function Prototypes in C++
Several advantages of Function Prototypes in C++ are as follows:
- Function prototypes in C++ can allows us to avoid run-time errors and enhance code reliability.
- It reduces the dependency between the header files, which helps to reduce the requirement for recompilation when they modify.
- By separating the function declaration from its implementation, function prototypes promote modular code design, which makes the program easy to manage and implement.
- During program compilation, function prototypes help to catch errors, such as mismatched argument types and incorrect numbers of arguments. It helps to reduce debugging time and enhance code reliability.
- Function prototype defines the parameter types and return values, which enables the compiler to perform type checking. It ensures that functions are invoked with the correct argument types, which prevents common errors.
Disadvantages of Function Prototypes in C++
Several disadvantages of Function Prototypes in C++ are as follows:
- If mismatched function prototypes and definition occurs in the program, it can cause to errors.
- It can increase the code size, which affects the performance of the program.
- In large-scale projects, synchronizing function prototypes with their particular definitions can be difficult. Any modification to the function signature requires multiple adjustments, resulting in more maintenance work.
- Function prototypes can make the code more difficult to read. Multiple declarations with complex signatures may make the source code less readable and harder to follow.
- It can lead to duplicated effort while defining the function signatures.
C++ Function Prototype MCQs
1) Which of the following options is the best description of a function prototype in C++?
- A declaration of a function's interface
- A function call
- A function definition
- None of the above
2) Where should a function prototype be placed in a program?
- After the function definition
- Inside the main function
- At the end of the program
- Before the function is called
3) Which of the following components is NOT included in a function prototype in C++?
- Return type
- Function body
- Function name
- Parameters
4) Why are function prototypes important in C++ recursive functions?
- They allow a function to call itself before it's fully defined
- They improve performance
- They reduce memory usage
- They avoid infinite loops
5) What happens if the function definition does not match the prototype in C++?
- Program runs slower
- Compiler throws an error
- Program still runs correctly
- The function is ignored.