Loading lessons...
Functions
Functions
A function is a named block of code that runs when you call it. They turn a huge program into tidy reusable pieces.
Defining a function
void myFunction() {
printf("I just got called!");
}
voidmeans "returns nothing".myFunctionis the name.- The
{ }hold the body.
Calling a function
int main() {
myFunction(); // runs the function
return 0;
}
Put definitions before use
In C, you usually define (or at least declare) a function before calling it. Later we'll meet prototypes that relax this.
Why use functions?
- Reuse: write once, call many times.
- Organization: code is easier to read in chunks.
- Testing: each function can be tested alone.
TL;DR
- A function bundles code under a name.
- Define with a return type, a name, and a body.
- Call it by name with parentheses:
myFunction();. - Functions make code reusable and organized.