7C. Side Effects,
Pure Functions and
Void Functions


Pure functions

In general, calling a function can (1) cause a side effect to occur and (2) return an answer. For example, random() returns an answer, but has a side-effect that causes two consecutive calls to random() to produce different results.

Many functions only produce a result; they have no side-effects. They are called pure functions. If f  is a pure function that takes one integer parameter, then two calls to f (3) will surely produce the same answer. For example, the sqrt function is pure. If you ask for the value of sqrt(16.0) many times, you will get result 4.0 every time.


Avoid duplicate calls to pure functions

The standards for this course require that a function must not call the same pure function more than once with the same parameter, in situations where it would be easy to avoid that, possibly by storing the result in a variable. For example, instead of

  int demo(const double x)
  {
    return f(x) + f(x) + pow(f(x+1), f(x+1));
  }
write
  int demo(const double x)
  {
    double z = f(x+1);
    return 2*f(x) + pow(z, z);
  }


Void functions

At the opposite extreme from pure functions are void functions, which have side-effects but do not return a result. To define a void function, just make the return-type be void. For example:

  void sayHello()
  {
    printf("Hello.\n");
  }

Since there is no result to return, there is no return statement. A void function stops when it reaches the end of its body.


Using a void function

You are required to ignore the result of a void function. For example,

  sayHello();
calls sayHello() and ignores its result, as required.


Exercises

  1. Can a pure function have a side effect? Answer