5
Functions

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.

When should I use a function?

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:

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​M​a​r​k​ ​h​a​s​ ​d​o​n​e​ ​a​s​ ​m​u​c​h​ ​C​o​c​o​a​ ​P​r​o​g​r​a​m​m​i​n​g​ ​a​s​ ​I​ ​c​o​u​l​d​ ​f​i​t​ ​i​n​t​o​ ​5​ ​d​a​y​s​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​B​o​ ​h​a​s​ ​d​o​n​e​ ​a​s​ ​m​u​c​h​ ​O​b​j​e​c​t​i​v​e​-​C​ ​P​r​o​g​r​a​m​m​i​n​g​ ​a​s​ ​I​ ​c​o​u​l​d​ ​f​i​t​ ​i​n​t​o​ ​2​ ​d​a​y​s​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​M​i​k​e​ ​h​a​s​ ​d​o​n​e​ ​a​s​ ​m​u​c​h​ ​P​y​t​h​o​n​ ​P​r​o​g​r​a​m​m​i​n​g​ ​a​s​ ​I​ ​c​o​u​l​d​ ​f​i​t​ ​i​n​t​o​ ​5​ ​d​a​y​s​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​T​e​d​ ​h​a​s​ ​d​o​n​e​ ​a​s​ ​m​u​c​h​ ​i​O​S​ ​P​r​o​g​r​a​m​m​i​n​g​ ​a​s​ ​I​ ​c​o​u​l​d​ ​f​i​t​ ​i​n​t​o​ ​5​ ​d​a​y​s​​n​"​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset