Definition and declaration

The definition of a function specifies exactly how a function is constructed, what parameters are passed to it, and what value it returns to the calling function.

With the declaration we name a variable and make it known to the compiler.

Definition and declaration differ in some points. The definition includes a memory allocation for the function, while no memory is allocated in the declaration. The declaration can be done several times, vice versa a function can be defined exactly once in a program.

Parameter vs. Argument

The terms parameter and argument are often used synonymously. Parameters are variables that are declared in the function signature. Arguments are values that are used when the function is called. Parameters are declared in round brackets of the function signature. The parameters generally dictate how a function must be called.

In programming languages, a distinction is made between two main forms of parameter passing: call-by-value and call-by-reference. Parameters can be passed to functions in C++ by value, by pointer or by reference.

Syntax

return_type function_name(parameter_list) {
    // Function body
}

Components of Function Syntax

  1. Return Type:
    • Specifies the type of value the function returns (e.g., int, float, void).
  2. Function Name:
    • The identifier used to call the function.
  3. Parameter List:
    • A comma-separated list of parameters, each with a type and a name. It can be empty if the function takes no arguments.
  4. Function Body:
    • Enclosed in curly braces {}, containing statements that define what the function does.

Code Example

#include <iostream>
using namespace std;

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

int main() {
    cout << add(5, 7);

    return 0;
}

Output

12

Code Explanation

Function Definition: add

int add(int a, int b) {
  • This defines a function named add that takes two integer parameters a and b and returns their sum as an integer.
Function Logic
    return a + b;

return a + b;

  • The function computes the sum of a and b and returns the result.
Calling the add Function
cout << add(5, 7);
  • The add function is called with arguments 5 and 7. The returned sum (which is 12) is then printed to the console using cout.

Program Termination

return 0;
  • This line indicates that the program executed successfully and terminates the main function.