7 Functions
This chapter covers
- An introduction to simple functions
- Working with
main
- Understanding recursion
We have already seen the different means that C offers for conditional execution: execution that, based on a value, chooses one branch of the program over another to continue. The reason for a potential “jump” to another part of the program code (for example, to an else
branch) is a run-time decision that depends on run-time data. This section starts with a discussion of unconditional ways to transfer control to other parts of our code: by themselves, they do not require any run-time data to decide where to go.
The code examples we have seen so far often used functions from the C library that provided features we did not want (or were not able) to implement ourselves, such as printf
for printing and strlen
for computing the length of a string. The idea behind this concept of functions is that they implement a certain feature once and for all and that we then can rely on that feature in the rest of our code.
A function for which we have seen several definitions is main
, the entry point of execution into a program. In this section, we will look at how to write functions ourselves that may provide features just like the functions in the C library.
The main reasons motivating the concept of functions are modularity and code factorization: