Chapter 5. Functions and Macros

Functions

Some things needs to be repeated. Code is not one of them. A function is a bundle of code that can get called any number of times, as often you wish.

Analogies are good. Let's explore an analogy that deals with waiters, chefs, pizzas, and functions. In English, when we say a person has a function, we mean that the person performs some very specific (usually, very important) task. They can do this task again and again and whenever they are called upon to do so.

The following comic strip shows the interaction between a waiter (caller) and a chef (callee). The waiter wants food for his table, so he calls upon the chef to prepare the food required by the waiting table.

The chef prepares the food and then returns the result to the waiter.

Functions

Here, the chef performs his function of cooking food. The chef accepted the parameters about what type of food to cook (three pepperoni pan pizzas). The chef then went away, did some work, and returned with three pizzas. Note that the waiter does not know and does not care about how the chef goes about cooking the pizzas. The chef abstracts away the process of cooking pizzas for the waiter, so cooking a pizza is just a simple, single-line command for the waiter. The waiter just wants his request to be completed and the pizzas returned to him.

When a function (chef) gets called with some arguments (types of pizzas to be prepared), the function performs some actions (preparing the pizzas) and optionally returns a result (the actual finished pizzas).

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

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