• Home
  • 6.2 Function Declaration

6.2 Function Declaration

View Categories

6.2 Function Declaration

1 min read

Table of Contents

A function declaration, also called a function prototype, informs the compiler about a function before the function is called or defined. It specifies the function’s name, return type, and parameter types.

A function can therefore be declared before main() and defined later in the source file. This allows the compiler to verify function calls even when the complete function definition has not yet been encountered.

Source Code #

#include <iostream>

int add(int, int);

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

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

    return 0;
}

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

Output #

Sum: 30

Explanation #

  • int add(int, int); is a function declaration.
  • The declaration specifies that add returns an int and accepts two int parameters.
  • Parameter names are optional in a function declaration, so only the parameter types are specified.
  • The semicolon at the end indicates that this is a declaration rather than a function definition.
  • main() can call add() because the compiler has already encountered its declaration.
  • add(10, 20) calls the function with two integer arguments.
  • The function definition appears after main().
  • int add(int a, int b) provides the function’s implementation and names its parameters.
  • return a + b; returns the calculated sum to the caller.
  • The declaration and definition must have compatible return types and parameter types.

Powered by BetterDocs

Leave a Reply

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