A program is a collection of functions. When you run a program, those functions are copied from the hard drive into memory, and the processor finds the function called “main” and executes it.
Remember that a function is like a recipe card. If you began to execute the “Easy Broiled Chicken” card, you would discover that the third instruction says “Execute the Seasoned Bread Crumbs recipe,” which is explained on another card. A programmer would say, “The Easy Broiled Chicken function calls the Seasoned Bread Crumbs function.”
Similarly, main() can call other functions. For example, main() in ClassCertificates called the congratulateStudent(), which in turn called printf().
While you are preparing the bread crumbs, you stop executing the steps on the “Easy Broiled Chicken” card. When the bread crumbs are ready, you resume working through the “Easy Broiled Chicken” card.
Similarly, the main function stops executing and “blocks” until the function it called is done executing. To see this happen, you are going to call a sleep function that does nothing but wait a number of seconds. This function is declared in the file unistd.h. At the top of main.c, include this file:
#include <stdio.h> #include <unistd.h> void congratulateStudent(char *student, char *course, int numDays) { …
In your main function, call the sleep function after the calls to congratulateStudent().
int main (int argc, const char * argv[]) { congratulateStudent("Kate", "Cocoa", 5); sleep(2); congratulateStudent("Bo", "Objective-C", 2); sleep(2); congratulateStudent("Mike", "Python", 5); sleep(2); congratulateStudent("Liz", "iOS", 5); return 0; }
Build and run the program. You should see a two-second pause between each message of congratulations. That is because the main function stops running until the sleep function is done sleeping.
Your computer came with many functions built-in. Actually, that is a little misleading – here is the truth: Before OS X was installed on your computer, it was nothing but an expensive space heater. Among the things that were installed as part of OS X were files containing a collection of precompiled functions. These collections are called the standard libraries.
Two of the files that make up the standard libraries are stdio.h and unistd.h. When you include these files in your program, you can then use the functions that they contain. printf() is in stdio.h; sleep() is in unistd.h.
The standard libraries have two purposes:
They represent big chunks of code that you do not need to write and maintain. Thus, they empower you to build much bigger, better programs than you would be able to do otherwise.
They ensure that most programs look and feel similar.
Programmers spend a lot of time studying the standard libraries for the operating systems that they work on. Every company that creates an operating system also has documentation for the standard libraries that come with it. You will learn how to browse the documentation for iOS and OS X in Chapter 16.