C - User Define Function
User-defined functions in C are functions that you create and define according to your program's specific requirements. These functions allow you to break down your program into smaller, manageable pieces of code, improving code organization, reusability, and readability. Here's a detailed explanation of user-defined functions in C:
return_type function_name(parameter_list) {
// Function body
// Statements and code to be executed
// Optional return statement
}
- return_type: Specifies the data type of the value returned by the function. It can be void if the function does not return a value or any valid C data type if the function returns a value.
- function_name: The name of the function, which should be unique within the program.
- parameter_list: The list of parameters (input) that the function accepts. Each parameter consists of a data type and a parameter name. Parameters are optional and can be empty if the function does not require any input.
Function Declaration:
Before using a user-defined function, you need to declare the function either above or before the point where it is called. The function declaration includes the return type, function name, and parameter list (if any).
Function Definition:
The function definition provides the implementation or code that is executed when the function is called. It includes the function body, which contains statements and code to be executed.
#include <stdio.h>
// Function declaration
void greet();
int main() {
// Function call
greet();
return 0;
}
// Function definition
void greet() {
printf("Hello, World!\n");
}
In this example, we have a user-defined function named greet(). It is declared above main() and defined below main(). The function takes no parameters (empty parameter list) and has a return type of void (no return value). When greet() is called inside main(), it prints "Hello, World!" on the console.
Passing Parameters and Returning Values:
User-defined functions can also accept parameters and return values. Parameters allow you to pass data into the function, and return values allow you to obtain results or values from the function.
#include <stdio.h>
// Function declaration
int addNumbers(int num1, int num2);
int main() {
int result = addNumbers(5, 10); // Function call
printf("The sum is %d\n", result);
return 0;
}
// Function definition
int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum; // Returning the sum
}
In this example, the addNumbers() function takes two integer parameters (num1 and num2) and returns their sum. Inside the function, the sum is calculated and stored in a variable sum. Finally, the sum is returned using the return statement. The returned value is then assigned to the result variable in main() and printed.
By using parameters and return values, you can create functions that perform specific tasks with the flexibility to handle different inputs and produce different outputs.