Friday, September 11, 2015

Functions

Previous Topic    Course Outline    Next Topic

Functions are basically set of commands that we can call over our program.

There are two main reasons why they exist:
  1. Readability. We don't want to flood our main() function with a lot of statements. The main function should only contains the main flow of the program.
  2. Re-usability. Instead of copy-pasting set of commands, we can define a function to hold it and call it whenever it is needed.
In C, this is the structure of a function,

1
2
3
4
5
6
int isGameOver(int noOfTries) {
    if (noOfTries > 10) {
        return 1;
    }
    return 0;
}

First, we have the function declaration (line 1) consists of return data type (int), function name (isGameOver) and parameters (noOfTries) separated by commas.

Right after the declaration, we have the function body.

When to create a function?
  • You have to perform something on a subject over and over gain. Define 'something' as the function body and the 'subject' as the parameter.
  • You don't want to clutter the main function. In this case, you put certain lines of code into a function with a void return type (use this when your function doesn't return anything), and even empty parameters.

Previous Topic    Course Outline    Next Topic

No comments:

Post a Comment