A function in C is a block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can write a function once and call it whenever needed.
Functions make C programs modular, reusable, easy to maintain, and easier to debug.
1. Types of Functions in C
C supports two main types of functions:
a) Library Functions
These are predefined functions provided by C libraries.
Examples:
printf()– Outputscanf()– Inputsqrt()– Square rootstrlen()– String length
Library functions require including header files like stdio.h, math.h, string.h, etc.
b) User-Defined Functions
These are custom functions created by the programmer.
Example:
int add(int a, int b) {
return a + b;
}
2. Advantages of Using Functions
✔ Makes code shorter and cleaner
✔ Promotes reusability
✔ Improves readability
✔ Breaks complex problems into smaller parts
✔ Allows teamwork — different people can work on different functions
3. Function Structure in C
Every C function has three main parts:
a) Function Declaration (Prototype)
Tells the compiler about the function name, return type, and parameters.
int add(int, int);
b) Function Definition
Actual body of the function.
int add(int x, int y) {
return x + y;
}
c) Function Call
Invokes the function.
int result = add(10, 20);
4. Syntax of a Function
return_type function_name(parameter_list) {
// function body
}
Examples of return types:
void→ returns nothingint→ returns an integerfloat→ returns a decimal valuechar→ returns a character
5. Parameter Types in Functions
a) Functions with No Parameters and No Return Value
void greet() {
printf("Hello!");
}
Call:
greet();
b) Functions with Parameters but No Return Value
void display(int n) {
printf("Number: %d", n);
}
c) Functions with Return Value but No Parameters
int getNumber() {
return 100;
}
d) Functions with Parameters and Return Value
int multiply(int a, int b) {
return a * b;
}
6. Example Program Demonstrating Functions
#include <stdio.h>
// Function declaration
int sum(int, int);
// Main function
int main() {
int a = 5, b = 10;
int result = sum(a, b); // Function call
printf("Sum = %d", result);
return 0;
}
// Function definition
int sum(int x, int y) {
return x + y;
}
7. Why Functions are Important in C
- Reduce code duplication
- Help organize large programs
- Enable structured programming
- Useful for modular development
- Make debugging easier
8. Special Function: main()
The main() function is the entry point of every C program.
int main() {
// code starts here
}
Without main(), a C program will not run.
Citations
🔗 View other articles about C Programming:
https://savanka.com/category/learn/c-programming/
🔗 External C Documentation:
https://www.w3schools.com/c/