C++ Function Declaration

A function declaration in C++ tells the compiler about a function's name, return type, and parameters. It is also called a function prototype. Declarations are used before calling the function in code.

1. Function Declaration Syntax

The basic syntax of a function declaration is:

C++
return_type function_name(parameter_list);

2. Function Declaration Example

This example shows a function declared before main() and defined after main().

C++
#include <iostream>
using namespace std;

// Function declaration
int add(int a, int b);

int main() {
    int sum = add(5, 3); // Calling function
    cout << "Sum: " << sum << endl;
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}

3. Common Mistakes

Forgetting to declare a function before calling it or mismatching the parameter types may cause compilation errors. Always ensure the declaration matches the definition.

Conclusion

Function declarations in C++ allow the compiler to know about functions before they are used. They help in organizing code, enabling modularity and reusability.