• Home
  • 6.7 Function Declarations and Definitions

6.7 Function Declarations and Definitions

View Categories

6.7 Function Declarations and Definitions

A function declaration specifies a function’s interface, including its return type and parameter types. A function definition provides the implementation that executes when the function is called.

#include <stdio.h>

int subtract(int a, int b);  /* Declaration */

int main(void)
{
    int result = subtract(20, 8);

    printf("Result = %d\n", result);

    return 0;
}

int subtract(int a, int b)   /* Definition */
{
    return a - b;
}

Example Output #

Result = 12

Explanation #

The declaration:

int subtract(int a, int b);

informs the compiler that subtract() returns an int and accepts two int parameters. It does not contain the function body.

The definition:

int subtract(int a, int b)
{
    return a - b;
}

provides the implementation. It calculates the difference between the arguments and returns the result.

Declaration vs. Definition #

Feature Function declaration Function definition
Specifies return type Yes Yes
Specifies parameter types Yes Yes
Contains function body No Yes
Ends with a semicolon after the parameter list Yes No
Provides the implementation No Yes

A function can be declared more than once when the declarations are compatible, but a function must not have multiple definitions in the same program where that violates C’s definition rules.

Function Defined Before Its Call #

A separate prototype is not necessary when the function definition itself appears before the call:

#include <stdio.h>

int subtract(int a, int b)
{
    return a - b;
}

int main(void)
{
    printf("%d\n", subtract(20, 8));
    return 0;
}

Here, the definition makes the function’s interface known before main() calls it.

Powered by BetterDocs

Leave a Reply

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