A function is a block of statements that takes inputs, performs a specific computation, and produces an output. The primary advantage of using functions is code reusability, eliminating the need to write the same code multiple times for different inputs. Instead, you can call the function whenever needed.
Below is a simple C program that showcases the use of functions:
#include <stdio.h>
// Function declaration
int add(int, int);
int main() {
int sum;
sum = add(10, 20); // Function call
printf("Sum: %d", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
A function declaration tells the compiler about the function’s return type, number of parameters, and their data types. While parameter names are optional in declarations, they are required in function definitions.
// Function that takes two integers as parameters and returns an integer
int max(int, int);
// Function that takes a char and an int as parameters and returns an integer
int process(char, int);
In C, functions can be declared and defined in the same place, as seen in the above example. However, for library functions, the declarations are found in header files, while the definitions are in library files.
When calling a function, values or references can be passed as arguments. These are classified into:
#include <stdio.h>
void fun(int x) {
x = 30;
}
int main() {
int y = 10;
fun(y);
printf("Value of y: %d", y); // Output: Value of y: 10
return 0;
}
#include <stdio.h>
void fun(int *ptr) {
*ptr = 30;
}
int main() {
int y = 10;
fun(&y);
printf("Value of y: %d", y); // Output: Value of y: 30
return 0;
}
main()
function, which serves as the entry point and is called by the operating system when the program is executed.int
, float
). If a function doesn’t return any value, void
is used.fun()
means that parameters are not specified, allowing any number of arguments.void fun()
and void fun(void)
explicitly indicate that no parameters are allowed.Functions in C enhance code modularity and reusability. Understanding function declarations, definitions, and parameter passing techniques helps in writing efficient and organized programs. Mastering these concepts is fundamental to developing robust C applications.