This is an old version, view current version.

9.9 Declarations

In general, functions must be declared before they are used. Stan supports forward declarations, which look like function definitions without bodies. For example,

real unit_normal_lpdf(real y);

declares a function named unit_normal_lpdf that consumes a single real-valued input and produces a real-valued output. A function definition with a body simultaneously declares and defines the named function, as in

real unit_normal_lpdf(real y) {
  return -0.5 * square(y);

A user-defined Stan function may be declared and then later defined, or just defined without being declared. No other combination of declaration and definition is legal, so that, for instance, a function may not be declared more than once, nor may it be defined more than once. If there is a declaration, there must be a definition. These rules together ensure that all the declared functions are eventually defined.

Recursive functions

Forward declarations allow the definition of self-recursive or mutually recursive functions. For instance, consider the following code to compute Fibonacci numbers.

int fib(int n);

int fib(int n) {
  if (n < 2) return n;
  else return fib(n-1) + fib(n-2);

Without the forward declaration in the first line, the body of the definition would not compile.