Introduction to Functions
A function is a named, self-contained block of code that performs a specific task. Instead of writing the same logic over and over again, you write it once inside a function and then call that function wherever you need the behavior. Every C program you have written so far already uses a function — main — even the smallest "Hello, World!" program is a single function that the operating system calls to start your program.
Why Functions Exist
As programs grow, three problems show up quickly: code gets duplicated, files get long and hard to follow, and it becomes hard to reason about which part of the program is responsible for what. Functions solve all three at once.
Reusability — write the logic once, call it from as many places as you need.
Organization — a large program becomes a set of small, named pieces instead of one giant block of statements.
Abstraction — the caller only needs to know what a function does and how to call it, not how it is implemented internally.
Anatomy of a Function
Every C function has four parts: a return type, a name, a parameter list, and a body.
Function syntax
return_type function_name(parameter_list) {
// body: statements that run when the function is called
return value; // only needed if return_type is not void
}Return type — the type of value the function sends back to its caller (e.g.
int,double,char). Usevoidif the function does not return anything.Name — how you refer to the function when calling it. Follows the same naming rules as variables.
Parameter list — the inputs the function accepts, written as a comma-separated list of
type namepairs. Can be empty.Body — the statements between
{ }that run each time the function is called.
Calling a Function
To use a function, you call it by writing its name followed by parentheses containing any arguments it needs. If the function returns a value, you can store that value, print it, or use it in an expression.
A first complete example
#include <stdio.h>
// Function definition: takes two ints, returns their sum
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main(void) {
int result = add(3, 4); // calling add() with arguments 3 and 4
printf("3 + 4 = %d\n", result);
// You can also call a function directly inside an expression
printf("5 + 6 = %d\n", add(5, 6));
return 0;
}Here, add is called twice. Each call runs the function body from the top, using the specific arguments passed in that call, and produces its own independent result.
Functions That Return Nothing: void
Not every function needs to hand a value back to its caller. A function might exist purely for its side effect — printing something, modifying data through a pointer, or updating global state. For these, the return type is void.
A void function
#include <stdio.h>
void greet(char name[]) {
printf("Hello, %s!\n", name);
// no return statement needed
}
int main(void) {
greet("World");
greet("C programmer");
return 0;
}