Using functions in your code
January 27, 2012 Leave a comment
This is for beginners. If you are an advanced programmer, you can skip this post 🙂
If you perform a common task in several parts of your program, instead of repeating the code several times in your code, you make that task a function to call.
Say if that common task is to play a Happy Birthday tune, which involves various tones and pauses, then you can define a function to do that.
void sing_happy_bday()
{
…
}
Now say some of your tasks involve playing this tune and other stuff, you can use a switch-case structure:
#define over_phone 1
#define home_visit 2
#define restaurant_celebration 3
int mode=over_phone;
…
…
void celebrate_bday()
{
switch (mode)
{
case over_phone:
call_bday_mom();
chat();
sing_happy_bday();
hang_up();
break;
case home_visit:
knock_on_door();
hug();
light_candle();
sing_happy_bday();
hug();
say_bye();
break;
case restaurant_celebration:
drive_to_restaurant();
wait_mom();
hug();
order_bday_cake();
light_candle();
sing_happy_bday();
hug();
pay();
exit_restaurant();
break;
}
}
In the above pseudo code, there are multiple functions that are called more than once, such as hug(), light_candle(), sing_happy_bday(). They are the smallest functional modules that are used many times in various parts of the code. Making them into functions makes the code easier to understand and avoid repeating code, which wastes memory space. Also, if you want to change how sing_happy_bday() is implemented, say from just singing into singing with a guitar, all you need to do is to change the sing_happy_bday() function. If you didn’t turn this module into function and repeated it several times in your code, you will need to modify several places to add the guitar. Mistakes happen when you have to modify several places. Maybe in a rare case, you will sing without the guitar, surprising the bday girl 🙂
Benefits of making modules into functions:
*No repeating code so saves memory
*Easy to modify code since the code only has one copy
*Program is easy to understand than packets of details
Drawbacks:
*Program runs slightly slowly (you won’t notice) since a jump is needed to get to the function and a jump is needed to return from the function
*I want to say more but came up short. Rarely do you need to think of the drawbacks 😉