By

Arduino Learning #4: Defining Functions

At this point in arduino learning, I'm sure you've seen the loop() and setuo() functions, but do we actually know what they are? And how can we define our own functions?

Functions are a saved set of instructions for the computer to reuse, so instead of re-writing all of the code you want to reuse, you can wrap your code in functions.

Functions can also have return values. Let's do an example I'm sure we're all familiar with.

You probably remember seeing functions like this in math class f(x) = x * x. Can you guess the return value of f(2)?

Let's try an example in C code.

int product( int x, int y )
{
    return x * y;
}

Breaking that down into to parts, we can see on the first line we declare the data type the function will return, in this case and int or integer. After we write product(, we tell the computer what arguments this function will take. Again we must specify the data type for each argument. Arguments must be comma-separated.

After the first line (int product(int x, int y)), where we declared the function return type, name, and arguments, we have the instructions, which we must place in between the {}.

The third line of the function (return x * y;), tells the function what to return.

Examples

Try and figure out the return values.

int a = product(1, 3);
int b = product(3, 5);
int c = product(8, 2);


// a = 3, b = 15, and c = 16 respectively.

More examples

// Notice how I didn't put the "{" on a new line. Style points.
float hypotenuse(int a, int b) {

    int cSquared = product(a, a) + product(b, b);

    // using the built-in sqrt() function to get the square root of a^2 + b^2
    return sqrt(cSquared);

}

Other important things.

Every language has their own style conventions for variable and function names.

In C, C++, JavaScript, objective C, and many others, you are supposed to use camelCase.

  • cammelCase
  • thisIsACamelCaseWord
  • hereIsAnotherCamelCaseExample

in Ruby, Python and a number of other languages, we use _, for breaking words apart.

  • ruby_variable
  • other_ruby_variable
  • first_name
  • last_name

And almost always, you won't be able to capitalize a variable. This is often enforced.

MY_VARIABLE would not fly in most languages, because all caps is reserved for use in constants.

Written by
Programmer, Entrepreneur, Startup Enthusiast