Defining and calling functions in C++

Functions in C++ are used to encapsulate a specific set of instructions that can be executed repeatedly throughout a program. Functions can be defined and called in C++ using the following syntax:

return_type function_name(parameter_list) {
    // function body
}

– `return_type` is the data type of the value returned by the function. If the function does not return a value, the return type is `void`.
– `function_name` is the name of the function.
– `parameter_list` is a comma-separated list of parameters that the function takes as input. If the function does not take any parameters, the parameter list is empty.

For example, the following function takes two integer parameters and returns their sum:

int sum(int a, int b) {
    return a + b;
}

To call a function in C++, you use the function name followed by parentheses containing the arguments, if any. For example:

int result = sum(3, 4);
cout << result << endl; // output: 7

In this example, the `sum` function is called with the arguments `3` and `4`, and the returned value is stored in the `result` variable.

Functions can be called from anywhere in the program, including within other functions. For example:

int multiply(int a, int b) {
    return a * b;
}

int calculate(int x, int y) {
   int result1 = sum(x, y);
    int result2 = multiply(x, y);
    return result1 + result2;
}

int main() {
    int a = 3, b = 4;
    int c = calculate(a, b);
    cout << c << endl; // output: 19 (3+4)+(3*4)
    return 0;
}

In this example, the `multiply` function is called from within the `calculate` function, and the `calculate` function is called from within the `main` function.

Functions can be very useful for organizing code, making it more modular and easier to understand. By defining and calling functions in C++, you can create programs that are easier to read, maintain, and extend.