What is a User-Defined Function?

A user-defined function in C is a function created by the programmer to perform specific tasks, rather than relying solely on built-in (library) functions. These functions are defined to meet the unique requirements of a program, enhancing modularity and enabling code reuse.

Why Do We Need User-Defined Functions?

User-defined functions offer multiple benefits that are especially important for creating scalable, efficient programs. Some of the primary reasons to use user-defined functions include:

Syntax:

Here's a basic syntax of User-defined Function:


return_type function_name(parameters) {
    // Function body
    return value; // Optional, depending on return type
}

Example:


#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
    return a + b;
}
// Function to multiply two numbers
int multiply(int a, int b) {
    return a * b;
}
int main() {
    int num1 = 5, num2 = 10;
    printf("Sum: %d\n", add(num1, num2));          // Calls the add function
    printf("Product: %d\n", multiply(num1, num2));  // Calls the multiply function
    return 0;
}

Output

Sum: 15 Product: 50

In this example:
The add function calculates the sum of two numbers, num1 and num2.
The multiply function calculates the product of two numbers, num1 and num2.

Using user-defined functions improves the program’s readability, as each function name clearly indicates its purpose. Additionally, these functions can be reused in other parts of the program or in other programs.