As programs become larger, writing all the code inside main() can make the program difficult to understand and maintain.
Functions help us divide a large program into smaller, reusable pieces.
What is a Function?
A function is a block of code designed to perform a specific task.
For example, instead of writing the same addition code multiple times, we can create a function for it and call that function whenever we need it.
void greet()
{
printf("Hello!");
}
We can call it using:
greet();
Why Use Functions?
Functions make programs:
Easier to understand
Reusable
Easier to test and debug
Better organized
For example, a large program could be divided into:
main()
├── calculateTotal()
├── checkResult()
└── displayResult()
Each function handles a specific task.
Creating a Function
A basic function looks like this:
return_type function_name()
{
// code
}
For example:
void greet()
{
printf("Hello, John!");
}
Here:
void→ return typegreet→ function name()→ parameters{ }→ function body
Calling a Function
Creating a function doesn't execute it. We need to call it.
#include <stdio.h>
void greet()
{
printf("Hello, John!");
}
int main()
{
greet();
return 0;
}
Output:
Hello, John!
When greet() is called, the code inside the function executes.
Function with Parameters
A function can receive values from the caller. These values are called parameters.
void greet(char name[])
{
printf("Hello, %s!", name);
}
We can call it like this:
greet("John");
The function receives "John" and uses it inside the function.
Function with a Return Value
A function can also calculate something and return a value.
For example:
int add(int a, int b)
{
return a + b;
}
Now we can use it:
int result = add(10, 20);
printf("%d", result);
Output:
30
Here, int indicates that the function returns an integer.
Four Common Types of Functions
Functions can be classified based on whether they take parameters and return a value.
Type | Example |
|---|---|
No parameter, no return |
|
Parameter, no return |
|
No parameter, returns value |
|
Parameter, returns value |
|
The last type is very common:
int add(int a, int b)
{
return a + b;
}
Function Declaration
Sometimes we call a function before its actual definition. In that case, we can declare it first.
int add(int, int);
int main()
{
printf("%d", add(10, 20));
return 0;
}
int add(int a, int b)
{
return a + b;
}
The first line is called a function declaration or prototype.
In Simple Words
A function is a reusable block of code that performs a specific task.
Instead of putting everything inside main(), we can divide our program into smaller functions.
For example:
Program
↓
┌──────┼──────┐
↓ ↓ ↓
input calculate output
This makes our C programs cleaner, easier to manage, and reusable.