How to Use Function declaration and definition in C++ ?


In C++, functions can be declared and defined separately. Function declaration tells the compiler about the function name, return type, and parameters. Function definition provides the actual implementation of the function.

Here's an example of function declaration and definition in C++:

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

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

In the above example, the function add is declared with its return type and parameters in the first line. Then, the function is defined with its implementation in the next lines.

Another way to declare and define a function is to use a function prototype. A function prototype is a declaration of the function that includes its name, return type, and parameters. It is usually placed at the beginning of the program before the main function.

Here's an example of using a function prototype:

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

int main() {
    int result = add(2, 3);
    return 0;
}

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

In the above example, the function add is declared using a function prototype before the main function. Then, the function is defined after the main function.

It is also possible to define a function inline using the inline keyword. This tells the compiler to replace the function call with the actual function code at compile time, which can improve performance for small functions.

Here's an example of using the inline keyword:

// Inline function definition
inline int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(2, 3);
    return 0;
}

In the above example, the function add is defined as an inline function using the inline keyword. The function call is replaced with the actual function code at compile time, which can improve performance.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.