What is a function?
A function is a named block of code that does one job. You have already used some: printf, scanf and sqrt are functions. main is a function too!
Think of it like this: A function is like a recipe card with a name, such as "Make Tea". Once it is written, you just say "Make Tea" whenever you want tea – you don't write out all the steps again.
Writing a function
#include <stdio.h>
void sayHello() {
printf("Hello there!\n");
printf("Welcome to C.\n");
}
int main() {
sayHello();
sayHello();
return 0;
}Output
Hello there! Welcome to C. Hello there! Welcome to C.
voidmeans the function gives nothing back (more on that soon).sayHellois the name we chose.- The code inside
{ }runs every time the function is called. sayHello();calls it. We call it twice, so its lines print twice.
Why use functions?
- No copy-paste: write the code once, use it many times.
- Easier to read:
printReceipt();says what it does. - Easier to fix: a bug only needs fixing in one place.
Write functions before main
C reads your file from top to bottom. A function must be known before it is called, so put your functions above main. (The next lessons show another way.)
Remember: Define a function once, above
main. Call it by writing its name followed by();.