functions

So far, we have written only one function for our programs. That function is main. We start our program with main and all our code goes between the curly brackets for main.

However, most programs are many many times larger than the programs we wrote. For example, our programs have been typically 20 to 30 lines of code max. Most applications are over a million lines of code. Trying to code all of it in main would make it impossible to understand or fix.

In programming we often look at modularity. That is we break down a problem into smaller pieces. How a program is broken down depends on the language. In C, a program is broken down into functions.

Here are two principles of software engineering that explain why we want to use functions

  • DRY (Don't Repeat Yourself) principle

  • KIS (Keep it Simple) principle

DRY (Don't Repeat Yourself)

The same task might have to be performed more than one time in a program. By writing the code in a function, you isolate the task into a single module. Using the this piece of code involves only calling the function with the appropriate arguments. If there is a bug in the function, you only need to fix it in one place. By not repeating your code in more than one place you isolate any future modifications to one place.

KIS (Keep it simple)

Creating a separate module for your function allows you to keep the function simple. Instead of trying to figure out the logic for the entire program you only need to worry about one small piece at a time.

Last updated