C User defined Function

In C programming, a user-defined function is a function that is created by the programmer to perform a specific task. This function can be called from various parts of the program and can be reused multiple times, enhancing code modularity and readability.

Structure of a User-Defined Function

A user-defined function typically consists of three main parts:

1. Function Declaration (Prototype):

This tells the compiler about the function’s name, return type, and parameters (if any). It is usually placed at the beginning of the file or in a header file.

Syntax:

return_type function_name(parameter_list);

2. Function Definition:

This provides the actual implementation of the function. It includes the body of the function, where the code to be executed is written.

Syntax:

return_type function_name(parameter_list) {
// body of the function
}

3. Function Call:

This is where the function is used in the program. The function call invokes the function and, if applicable, passes arguments to it and/or receives a return value.

Syntax:

function_name(argument_list);

Example of a User-Defined Function

#include <stdio.h>

// Function Declaration (Prototype)
int add(int a, int b);

int main() {
    int result;

    // Function Call
    result = add(10, 20);

    printf("The result is: %d\\n", result);

    return 0;
}

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

Output:

The result is: 30

Explanation:

1. Function Declaration:

• int add(int a, int b);

• This informs the compiler that there is a function named add that takes two int parameters and returns an int.

2. Function Definition:

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

• This defines what the add function does. It takes two integers, adds them, and returns the result.

3. Function Call:

• result = add(10, 20);

• This calls the add function with arguments 10 and 20, and stores the result in the variable result.

Key Points:

Return Type: Specifies the type of value the function returns. If the function doesn’t return a value, use void as the return type.

Function Parameters: These are the inputs to the function. They can be used within the function to perform operations.

Function Body: Contains the code to be executed when the function is called.