Function Prototype In C++ - C++ Programming Tutorial
C++ Course / Design Patterns / Function Prototype In C++

Function Prototype In C++

BLUF: Mastering Function Prototype In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Function Prototype In C++

C++ is renowned for its efficiency. Learn how Function Prototype In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, a function prototype serves as a declaration that conveys details about the function's parameters and return value data types. Function prototyping in C++ is highly beneficial as it offers essential insights into the function's interface, including the parameter count, data types, and return value type, aiding the compiler in understanding the function's structure.

In the C++ programming language, a function prototype serves as a declaration providing the compiler with essential details such as the function's name, return type, and the quantity and data types of its parameters. This declaration plays a crucial role in verifying the accuracy of function calls prior to the actual function definition.

Syntax

It has the following syntax:

Example

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 examine the prototype for this function:

Example

int add ( int a1 , int a2 ) ;

here,

  • return type: int
  • name of the function: add
  • argument list: (int a1, int a2)

Since a semicolon is present after each function prototype, it will be included in the upcoming function prototype, similar to the one 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 type returned by a function determines the data type that is transmitted back to the program that invoked it. When a function has a return type of void, it means that the function does not yield any data. This is typically employed for tasks that involve actions like displaying output or modifying external data without providing feedback on the outcome.

1) Void Return Type

A void return type in C++ indicates that a function carries out an operation without returning any value. This is suitable for tasks like presenting output, recording information, or modifying a user interface where the caller does not need any specific output.

Syntax

It has the following syntax.

Example

void function_name(parameter_list);

C++ Example for Void Return Type

Let's consider an example to demonstrate the function prototype with a void return type in C++.

Example

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:

Output

Hello! This is Cpp Tutorial Company

Explanation:

The code defines a Display function which has a return type of void and displays an invoice message containing the specified company name. This function is called within the main function using the parameter "Cpp Tutorial Company", resulting in the message "Hello! This is Cpp Tutorial Company".

2) Integral return type:

In C++, integral return types (such as int, char, bool, and long) are employed when a function needs to return a whole number, character code, or boolean value. These types are suitable for tasks involving computation, assessment, or tallying.

Syntax

It has the following syntax.

int add(int x, int y)

C++ Internal Return Type Example

Let's consider an example to demonstrate the function prototype with the return type of int in C++.

Example

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:

Output

The total price is: 500

The Grade achieved is: B

17 is an odd number.

Factorial of 6 is: 720

Explanation

In this instance, we showcase the application of various essential return types through addition, grade assignment, evenness verification, and factorial calculation. Within the main function, it sums two costs, evaluates a grade according to scores, checks if a number is odd or even, and calculates the factorial of a number, showcasing all outcomes.

3) Floating-Point Return Types

When a function needs to provide results containing fractions or decimal values, it utilizes floating-point return types like float or double. These types are crucial for accurately representing real numbers, especially in scientific computations, measurements, or financial analysis where precision is paramount.

Syntax

It has the following syntax.

Example

return_type function_name(parameters_list);

C++ Floating-Point Return Types Example

Let's consider an instance to demonstrate the function prototype with a floating-point return type in C++.

Example

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:

Output

The result of division is: 5

Explanation

In this instance, we create a divide function that securely divides two double values, managing division by zero by raising an error and yielding 0.0 as the result. Within the main function, the divide(20.0, 4.0) function is executed, the outcome of 5 is calculated, and then displayed on the console.

4) User-Defined Object Return Types:

C++ enables the creation of custom classes, enabling the return of objects from these classes. This approach encapsulates both data and functionality, facilitating the development of maintainable and structured code. The practice of returning objects from functions is frequently utilized when there is a requirement to instantiate a class and provide it to the caller for direct interaction.

Syntax

It has the following syntax.

Example

return_type function_name(parameters_list);

C++ User-Defined Object Return Types Example

Let's consider an instance to demonstrate the function prototype in C++ that returns a User-Defined Object type.

Example

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:

Output

Book Title: 1984

Book Author: George Orwell

Scope of Function Prototypes in C++

In C++, the range of a function prototype determines the locations within the program where the function can be called and used. This declaration introduces the function's name to the compiler, enabling it to be invoked before its concrete implementation.

We can classify the range of function prototype into two categories:

  • Global Context
  • Local Context

Let's now explore these categories with the assistance of a few illustrations.

1) Global Scope

When a function prototype is defined in the global scope, it becomes available throughout the entire program. This provides enhanced flexibility in structuring code, especially in extensive programs where function definitions might be placed after their invocations.

C++ Global Scope Example

Let's consider an illustration to showcase the Global Scope of Function Prototypes in C++.

Example

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:

Output

The addition of two numbers are: 23

Explanation

In this instance, we are outlining a function named total that performs addition on two whole numbers. Within the main function, it invokes total(15, 8), and subsequently saves the outcome in ans. Ultimately, the program displays the result.

2) Local Scope

In the local scope of C++, a function prototype is defined within the scope of a single function, limiting its accessibility to only that specific function. Invocation of this function is restricted to the function in which it is declared.

C++ Local Scope Example

Let's consider an illustration to showcase the Local Scope of Function Prototypes in C++.

Example

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:

Output

The difference between two numbers are: 13

Explanation

In this instance, we are outlining a function named subtract that computes the variance between two whole numbers. Within the main function, it invokes the subtract(18, 5) function, captures the outcome in ans, and ultimately displays the result.

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

a) They permit a function to invoke itself prior to being completely defined

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience