• Home
  • 6.1 Function Definition

6.1 Function Definition

View Categories

6.1 Function Definition

A function definition specifies the operations performed when a function is called. It includes the return type, function name, parameter list, and function body.

#include <stdio.h>

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

int main(void)
{
    int sum = add(10, 20);

    printf("Sum = %d\n", sum);

    return 0;
}

Example Output #

Sum = 30

Explanation #

The function definition begins with:

int add(int a, int b)

Its components are:

Component Description
int Return type of the function
add Function name
int a First parameter
int b Second parameter
{ ... } Function body

The statement:

int result = a + b;

adds the two parameter values and stores the result in result.

The statement:

return result;

returns the calculated integer to the calling function.

In main(), the expression add(10, 20) calls add() with the arguments 10 and 20. The returned value is assigned to sum.

Function Definition Syntax #

return_type function_name(parameter_list)
{
    /* Function body */
    return value;
}

For a function that does not return a value, use void as its return type:

void display(void)
{
    printf("Hello\n");
}

Here, the first void specifies that the function returns no value, while the void inside the parentheses specifies that it accepts no parameters.

A function definition provides the implementation of a function. A declaration can make its interface known before the definition appears.

Powered by BetterDocs

Leave a Reply

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