BETA Try the new lesson view
Theory

Functions

Why functions

The main of topic 3's program grew to 60 lines: input, checks, a switch, statistics, all in one place. Code like that is hard to read and even harder to fix.

A function is a named piece of code: it gets values, does something with them and returns a result. You have already used printf and read_int. Now you write your own.

The parts of a function

int round_to_int(double x) {
    return (int)(x + 0.5);
}
Part Here What it means
return type int the type of the result the function returns
name round_to_int how you call it
parameters (double x) what the function gets; each with its own type
body { ... } what it does
return return (int)(x + 0.5); ends the function and returns the result

A call is the name with the arguments in parentheses:

int p = round_to_int(8.75);

The program jumps into round_to_int, x gets 8.75, return returns 9, and 9 is stored in p.

void: no result or no parameters

void print_in_words(int grade) { ... }
int read_grade(void) { ... }
  • void in place of the return type: the function returns nothing, it only does something (e.g. prints). return; is optional here.
  • (void) in place of the parameters: the function gets nothing. Write (void), not (): in C empty parentheses mean "parameters not stated", and the compiler would not check what you pass.

Parameters are copies

A function gets a copy of the argument. Whatever it does with its parameter doesn't touch the caller's variable:

void double_it(int x) {
    x = x * 2;
}

int main(void) {
    int a = 5;
    double_it(a);
    printf("%d\n", a); /* 5 */
}
maindouble_it a5 x5 → 10 a copy stays 5gone after return

For a function to change the caller's variable you need pointers (topic 8). For now, return the result with return.

Local variables

A variable declared inside a function is local: it appears when the function is called and disappears when it ends. Other functions can't see it. So two functions can each have a variable sum, and they are two different variables.

Declare first, then use

The compiler reads the file from top to bottom. When main calls round_to_int, the compiler must already know that the function exists and which parameters it has. Two ways:

  • write the function above main (you do it this way in this topic);
  • above main write only the prototype, the first line with a ;, and the whole function below:
int round_to_int(double x);   /* the prototype */

int main(void) { ... round_to_int(8.75) ... }

int round_to_int(double x) { ... }

You'll need prototypes in topic 7, when the program splits into several files.

When to make a function

  • You are writing the same code a second time.
  • You can name a piece of code with one action: read_grade, print_in_words.
  • main no longer fits on the screen.

Names: an action gets a verb (read_, print_), a yes/no question gets is_ (is_valid).