C - Functions
Functions are blocks of code that perform specific tasks. They allow you to break down your program into smaller, modular pieces, making the code more organized, reusable, and easier to understand. There are two types of functions in C: predefined functions and user-defined functions.
Predefined Functions:
Predefined functions are provided by the C standard library and are available for use without any additional code. These functions perform common tasks and are included in header files such as <stdio.h> and <stdlib.h>. Examples of predefined functions include printf(), scanf(), strlen(), malloc(), and rand(). You can directly use these functions in your program by including the relevant header file.
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
In this example, printf() is a predefined function that displays the "Hello, world!" message on the console.
User-defined Functions:
User-defined functions are created by the programmer to perform specific tasks based on their requirements. These functions are defined by the programmer and can be called and reused throughout the program. User-defined functions are helpful for code organization, modularity, and reusability. You can define your functions to perform custom tasks and encapsulate functionality.
#include <stdio.h>
// Function declaration (also known as function prototype)
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) {
return num1 + num2;
}
In this example, the addNumbers() function is a user-defined function that takes two integer parameters and returns their sum. The function is declared before main() using a function prototype, and its definition follows main(). Inside main(), the function is called with arguments, and the returned value is printed.