C Functions
A function is a block of code that runs only when you call it. Functions let you write a piece of logic once and reuse it as many times as you like. This keeps your programs shorter, easier to read, and easier to fix. In fact you have already been using one important function on every page: main().
Why Use Functions?
Imagine you need to print a welcome message in five different places. Without functions you would copy the same printf() lines five times. With a function you write it once and call it by name whenever you need it. This idea is often called 'don't repeat yourself'.
- Reuse code without copying and pasting it
- Break a big problem into small, named steps
- Make programs easier to read and to test
- Fix a bug in one place instead of many
Creating and Calling a Function
To create a function you write a return type, a name, a pair of parentheses, and a body inside curly braces. To use it you simply write its name followed by parentheses. The example below creates a function called greet() and calls it from main().
Define and call a simple function
#include <stdio.h>
void greet() {
printf("Welcome to C programming!\n");
}
int main() {
greet();
greet();
return 0;
}Declaring Functions Before main()
C reads your file from top to bottom, so a function must be known before it is called. In the example above we defined greet() above main(). If you prefer to keep main() first, you can instead write a declaration (also called a prototype) at the top and put the full definition below.
Using a function prototype
#include <stdio.h>
void greet();
int main() {
greet();
return 0;
}
void greet() {
printf("Hello from a function!\n");
}Returning a Value
A function can also send a value back to the caller. You set the return type (for example int) and use the return keyword to hand back a result. The caller can then store or print that result.
A function that returns a number
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
int result = square(5);
printf("5 squared is %d\n", result);
return 0;
}Parts of a function
Exercise: C Functions
What must a C function that is declared to return a value always include?