Friday, July 22, 2011

Functions and its Basic


Up until this point, every line of code we've shown you has done a simple task, such as performing an arithmetic operation, or checking a boolean condition, or assigning to a variable. Functions allow you to do a whole lot in one line of code. Instead of performing a simple task, a single line of code can display a menu of choices, or compute complicated three-dimensional transformations, or even play Tetris!

How is this possible? Functions allow you to group a series of steps under one name. Remember in Section 1.1 when we were baking chocolate chip cookies? We had to perform the following steps:

place two eggs in a bowl
add 1.5 c. butter to the eggs
...
bake cookies for 10-12 minutes at 375 degrees or until brown
In C++, and in most programming languages, you can give a name to a series of steps. Let's say we want to call this procedure "bake cookies". Then, our algorithm for baking cookies becomes:

bake cookies

We've just created a function to do the work for us. Don't get too excited - you still need to know how to bake the cookies. You still need to know that the first step is placing two eggs in a bowl, and that the second step is adding butter to the eggs. In this example, what you would do is write a function called bakeCookies (C++ won't let you put spaces in the names of functions or variables) that performs the series of steps above, and then whenever you wanted to bake cookies, you would call the function bakeCookies, which would execute the lines of code necessary to carry out the procedure.
Note: When we say you are calling the function bakeCookies, we do not mean that you are giving it the name bakeCookies - you've already done that by writing the function. We mean you are executing the code in the function bakeCookies. "Calling a function" really means "telling a function to execute".

What are functions good for?

At this point, we've seen one reason why functions are useful. Functions let us create logical groupings of code. If someone is reading your code, and she sees that you call a function bakeCookies, she knows immediately that you are baking cookies. If, on the other hand, she sees that your code places eggs in a bowl, then adds butter, etc., it will not be clear right away that you are trying to bake cookies. Lots of recipes start out with putting eggs in a bowl, and lots of recipes add butter to the eggs. By the time she reads the last line, she might realize that you are baking cookies, but only if she is familiar with the recipe. It's possible that she won't realize that you are baking cookies at all! The point is, functions make your code much easier to read.
There is an even better reason to use functions: they can make your code shorter. Fewer lines of code is not always desirable, but every time you write a line of code, there's the possibility that you are introducing a bug. Functions start to reduce the number of lines of code when you call them repeatedly.
Suppose that you want to mail out invitations to eight of your friends for a cocktail party. Let's assume that you need to do the following procedure in order to invite your friend Hank.

  write Hank's name on the invitation
  write Hank's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

It takes five lines of pseudo-code to invite one friend, so it takes 40 lines of pseudo-code to invite eight friends. It would look like this:

  write Hank's name on the invitation
  write Hank's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

  write Ann's name on the invitation
  write Ann's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

  write Alicia's name on the invitation
  write Alicia's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

  write Whitney's name on the invitation
  write Whitney's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

  write Greg's name on the invitation
  write Greg's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

  write Mi Young's name on the invitation
  write Mi Young's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

  write Flavio's name on the invitation
  write Flavio's name and address on the envelope
  place the invitation on the envelope
  seal and stamp the envelope
  drop the envelope in the mail

  write Brian's name on the invitation
  write Brian's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

That's a lot of repeated code, and any time you repeat code like this, you are more likely to add a bug to your program. For example, look at what we're doing with Flavio's invitation - we are placing it on, not in, the envelope! We sealed his envelope and dropped it in the mail, but there was no invitation inside. Flavio will receive an empty envelope and he'll be mighty confused. That's a mistake that resulted from having to type the same lines of code over and over again.

Functions can substantially reduce the amount of pseudo-code you need to write to invite your eight friends to the party. It seems unlikely that you'd be able to reduce this at all - each of your friends has got to have their own personally addressed invitation, and all of the envelopes have to be sealed and stamped and placed in the mail. How are we going to reduce the number of lines of code? Let's create a function called inviteToParty which does the following procedure:

  write Hank's name on the invitation
  write Hank's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

Now that we have this function, we can call it eight times to invite our eight friends:

  inviteToParty
  inviteToParty
  inviteToParty
  inviteToParty
  inviteToParty
  inviteToParty
  inviteToParty
  inviteToParty

You probably noticed a problem with doing it this way. We're inviting Hank eight times, and none of our other friends are going to receive invitations! Hank will get invited eight times because the function invites Hank to the party, and the function is being called eight times. The solution is to modify the function so that it invites friend to the party, where friend can be any of your friends. We'll change our function so that it looks like this:

  write friend's name on the invitation
  write friend's name and address on the envelope
  place the invitation in the envelope
  seal and stamp the envelope
  drop the envelope in the mail

and then we'll change the way in which we call the function:

  inviteToParty (friend = Hank)
  inviteToParty (friend = Ann)
  inviteToParty (friend = Alicia)
  inviteToParty (friend = Whitney)
  inviteToParty (friend = Greg)
  inviteToParty (friend = Mi Young)
  inviteToParty (friend = Flavio)
  inviteToParty (friend = Brian)

Now, each time we call the function, friend is a different person, and each of our eight friends will be invited. We've just reduced the number of lines of pseudo-code from 40 to 13 by using a function, and our code became much easier to read. (We also got rid of that bug whereby Flavio received an empty envelope.)
All of the examples on this page were written in pseudo-code, but the next page describes how to write functions in C++.

Summary

Think of a function as a black box.





A "black box" is a convenient analogy for something that happens by magic. How does the black box work? It takes some inputs, and swirls them around inside the box, and produces some kind of output. Each function can swirl around the inputs in a different way, however that function so chooses. How a function will use the inputs to come up with the outputs is the essence of the function.

We just said that functions are like black boxes because we throw in some inputs, and something happens by magic, and some output comes flying out. The black box metaphor is really only appropriate when you are using other people's functions. When you write the function yourself, you have to know exactly how the function swirls up the inputs. It's not magical for you, because you decided how the function works. However, if you give your function to someone else for them to use, you can tell them it's a black box.

Basics of the function:

Now that you know what a function is, let's look at function syntax. We've already seen that a function can take some inputs, do some stuff, and then produce an output.

The basic form of a function definition is this:

output function_name (input_1, input_2, input_3, input_...) {
   // code to execute inside function
}

It's called a function definition because we are defining the function. We are saying, "This is a function named function_name, whose inputs are input_1, input_2, etc., and whose output is output. When it is called, the function will execute the code in between its curly braces ({}).
At this point, let's refine our sample function definition. When programmers talk about functions, instead of the word input they usually use the word parameter. A parameter to a function is nothing more than an input to a function. At the same time, instead of using the word output, programmers generally refer to the return of a function. A particular function "returns" a value. So, here is our updated function definition:

return_type function_name (parameter_1, parameter_2, parameter_3, parameter_...) {
   // code to execute inside function
}

Notice that in place of output, the function definition says return_type. That's because when we are actually writing a function definition, we'll put the return type there, immediately preceding the name of the function. The return type is nothing more than a plain old variable type, such as int, or double, etc.
Similarly, parameters use variable types also. If the first input to a function is an int, then the first parameter will be something like int my_number. We'll see what my_number does in just a moment.

A Real Function!

Enough dilly-dally, let's see a real, working, C++ function that actually does something! Suppose we need a function that, converts a temperature from Celsius to Fahrenheit. Here it is:


No comments:

Post a Comment