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.
A user-defined function typically consists of three main parts:
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.
return_type function_name(parameter_list);
This provides the actual implementation of the function. It includes the body of the function, where the code to be executed is written.
return_type function_name(parameter_list) {
// body of the function
}
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.
function_name(argument_list);
#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;
}
The result is: 30
• 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.
• 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.
• result = add(10, 20);
• This calls the add function with arguments 10 and 20, and stores the result in the variable result.
• 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.