cpp define function

Here is an example of defining a function in C++:

#include <iostream>

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

int main() {
    int num1 = 5;
    int num2 = 10;
    int sum = add(num1, num2);
    std::cout << "The sum is: " << sum << std::endl;
    return 0;
}

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

Explanation:

  • The first line #include <iostream> is a preprocessor directive that includes the input/output stream library in our program. This library provides functionality for input and output operations.

  • The next line int add(int a, int b); is a function declaration. It tells the compiler that there is a function named add which takes two integer parameters a and b, and returns an integer value.

  • The main function is the entry point of the program. It is where the execution of the program starts.

  • Inside the main function, two integer variables num1 and num2 are declared and assigned values 5 and 10 respectively.

  • The add function is called with num1 and num2 as arguments, and the return value is stored in the sum variable.

  • The std::cout statement is used to output the result to the console. It prints the string "The sum is: " followed by the value of sum.

  • The return 0; statement indicates the end of the main function and the successful execution of the program.

  • Finally, outside the main function, the add function is defined. It takes two integer parameters a and b, and returns the sum of a and b.

This is a basic example of defining a function in C++. The function declaration informs the compiler about the existence of the function, and the function definition provides the implementation of the function.