Getting started – our sample library
This chapter's example code has two pieces: a library that defines a public function and a console application that calls this function. Libraries are a great way to break up your applications, and while this example is simple, it also lets me show you how to create a library and include it in your application.
I'm going to stretch your imagination a bit; let's pretend that you're responsible for setting up a library of math functions. In this example, we'll only write one function, factorial. You should be able to recollect the factorial function from introductory programming; it's represented by a !
and is defined as follows:
0! is 0
1! is 1
n! is n × (n - 1)!
This is a recursive definition and we can code it in the following way:
unsigned long factorial(unsigned int n) { switch(n) { case 0: return 0; case 1: return 1; default: return n * factorial(n-1); } }
An alternate definition that avoids the cost of function calls...