In Chapter 3, you learned that a variable is a name associated with a chunk of data. A function is a name associated with a chunk of code. You can pass information to a function. You can make the function execute code. You can make a function return information to you.
Functions are fundamental to programming, so there is a lot in this chapter – three new projects, a new tool, and many new ideas. Let’s get started with an exercise that will demonstrate what functions are good for.
Suppose you are writing a program to congratulate students for completing a Big Nerd Ranch course. Before worrying about retrieving the student list from a database or about printing certificates on spiffy Big Nerd Ranch paper, you want to experiment with the message that will be printed on the certificates.
Create a new C Command Line Tool named ClassCertificates. (Select File → New → Project... or use the keyboard shortcut Command-Shift-N to get started.)
Your first thought in writing this program might be:
int main (int argc, const char * argv[]) { printf("Kate has done as much Cocoa Programming as I could fit into 5 days.n"); printf("Bo has done as much Objective-C Programming as I could fit into 2 days.n"); printf("Mike has done as much Python Programming as I could fit into 5 days.n"); printf("Liz has done as much iOS Programming as I could fit into 5 days.n"); return 0; }
Does the thought of typing all this in bother you? Does it seem annoyingly repetitive? If so, you have the makings of an excellent programmer. When you find yourself repeating work that is very similar in nature (in this case, the words in the printf() statement), you want to start thinking about a function as a better way of accomplishing the same task.