Back in Chapter 3, I introduced the idea of a variable: 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’s a lot in this chapter – three new projects, a new tool, and many new ideas. Let’s get started with an exercise that demonstrates 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.
To do that experiment, create a new project: a C Command Line Tool named ClassCertificates.
Your first thought in writing this program might be:
int main (int argc, const char * argv[]) { printf("Mark has done as much Cocoa Programming as I could fit into 5 daysn"); printf("Bo has done as much Objective-C Programming as I could fit into 2 daysn"); printf("Mike has done as much Python Programming as I could fit into 5 daysn"); printf("Ted has done as much iOS Programming as I could fit into 5 daysn"); 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.