• Home
  • 6.3 Function Definition

6.3 Function Definition

View Categories

6.3 Function Definition

< 1 min read

Table of Contents

A function definition provides the complete implementation of a function. It specifies the function’s return type, name, parameters, and the statements that are executed when the function is called.

A function definition must contain a function body enclosed in braces. The definition can appear before or after the code that calls the function, provided that a declaration is available before the call when required.

Source Code #

#include <iostream>

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

int main()
{
    int result = add(10, 20);

    std::cout << "Sum: " << result << '\n';

    return 0;
}

Output #

Sum: 30

Explanation #

  • int add(int a, int b) is the function definition for add.
  • int specifies that the function returns an integer value.
  • add is the name of the function.
  • a and b are the function parameters.
  • The statements enclosed in {} form the function body.
  • return a + b; calculates the sum and returns the result to the caller.
  • add(10, 20) calls the function and passes 10 and 20 as arguments.
  • The returned value is stored in the variable result.
  • Because the complete function definition appears before main(), a separate function declaration is not required in this example.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *