C Functions
A function is a reusable block of code that performs a specific task. Functions help organize code, avoid repetition, and make programs easier to test and maintain.
Every C function has a return type, a name, a parameter list, and a body. main() itself is just a special function that the operating system calls to start your program.
returnType functionName(parameters) {
// code
return value;
}Defining a function
A function definition specifies its return type, name, parameters in parentheses, and a body in braces. Use `return` to send a value back to the caller.
Calling a function
You call a function by writing its name followed by parentheses containing any arguments, like `add(2, 3)`. The function's return value can be stored, printed, or used in expressions.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
printf("%d\n", add(2, 3));
return 0;
}5add() takes two ints, returns their sum, and main() prints the result.
#include <stdio.h>
void greet() {
printf("Hello!\n");
}
int main() {
greet();
return 0;
}Hello!A void function performs an action but returns nothing.
Key points
- Functions have a return type, name, parameters and a body.
- void functions perform an action but return no value.
- Functions help avoid duplicated code and improve organization.
- main() is the special entry-point function of every program.
