C Functions
C functions are named blocks of code that perform a specific task. You write a function once and call it as many times as you need, which keeps programs short, organized and easy to test.
Defining and Calling a Function
A function has a return type, a name, a parameter list and a body. void means it returns nothing.
#include <stdio.h>
void greet(const char *name) {
printf("Hello, %s!\n", name);
}
int main(void) {
greet("Sara");
greet("Omar");
return 0;
}Hello, Sara! Hello, Omar!
Return Values and Prototypes
A function must be declared before it is called. If you define it below main, add a prototype (the first line followed by a semicolon) above main.
#include <stdio.h>
double average(int a, int b); // prototype
int main(void) {
printf("Average: %.1f\n", average(7, 10));
return 0;
}
double average(int a, int b) {
return (a + b) / 2.0;
}Average: 8.5
Pass by Value
C copies arguments into parameters. Changing a parameter inside the function does not affect the caller's variable. To change the original you pass a pointer, covered in the pointers lesson.
#include <stdio.h>
void tryToChange(int n) {
n = 99;
}
int main(void) {
int value = 1;
tryToChange(value);
printf("value is still %d\n", value);
return 0;
}value is still 1
Recursion in C
A recursive function calls itself. It needs a base case that stops the recursion.
#include <stdio.h>
unsigned long long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
int main(void) {
printf("10! = %llu\n", factorial(10));
return 0;
}10! = 3628800
Variable Scope
- Variables declared inside a function are local and exist only while it runs.
- Variables declared outside all functions are global and visible everywhere after their declaration.
- A static local variable keeps its value between calls.
- Prefer local variables and parameters; globals make code harder to follow.
Frequently asked questions
What is a function prototype in C?
A prototype is a declaration that tells the compiler a function's name, return type and parameter types before its full definition appears. It lets you call functions defined later or in other files.
Can a C function return multiple values?
Not directly. You can return a struct that holds several values, or pass pointers to variables that the function fills in.
Is C pass by value or pass by reference?
C is always pass by value. Passing a pointer copies the address, which lets the function modify the original data, so it simulates pass by reference.