Arduino - FunctionDeclaration

Arduino

Guide

Tutorials

Reference

Hardware

Software

Forum

Playground

Exhibition

Hacking

FAQ

Buy

Language | Libraries | Comparison

## Functions

Functions allow you to create modular pieces of code that perform certain tasks and then return you to the area of code it was executed from. The typical case for creating a function is when you need to perform the same action.

For instance, we move a student up a grade if they are old enough, or if they have passed a test, but only if they have paid their tuition.

    if (student_age > x) {
      if (tuition == "paid") {
        student_grade++;
      }
    }
    if (test_score > y) {
      if (tuition == "paid") {
        student_grade++;
      }
    }

However, if we later want to change tuition to a numerical test showing that they owe us less than a hundred dollars -- tuition < 100; -- we have to change the code in two places, greatly increasing the risk of bugs if we change it one place and forget to change it in the other.

A function helps by giving a block of code a name, then letting you call the entire block with that name. As a result, when you need to changed the named code, you only have to change it in one place.

Our function looks like this:

    // tell us the type of data the function expects
    void tuitionTest(int tuition_balance) {
      if (tuition_balance < 100) {
        student_grade++;
      }
    }

And our code looks like this:

    if (student_age > x) {
      tuitionTest(tuition_balance);
    }
    if (test_score > y) {
      tuitionTest(tuition_balance);
    }

### Prototyping, prior to 0004

If you are using a version of Arduino prior to 0004, any function you create yourself the in the body of your code needs a function prototype at the beginning of your code, before the setup() code block. This is similar to the declaration of a variable, and essentially is just the first line of your function declaration, with a semicolon at the end.

    void displayNumber(int incomingValue);

This tells Arduino what kind of function you are calling and what arguments it will pass.

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

Edit Page | Page History | Printable View | Recent Site Changes