Functions and Structured Programming

As we mentioned in Chapter 1, a C function is a collection of statements, enclosed in braces ({}), which performs a particular task. It can receive arguments (data) and also return a value.

Functions allow you to program with a “divide and conquer” strategy. Rather than try to solve a large problem all at once, you break the problem into several parts and attack each one separately. This approach, known as “structured programming,” allows you to write clear, reliable programs that perform separate tasks in discrete, logically contained modules. In the C language, these modules are called functions.

Functions offer several advantages. They can

Make programs easier to write and read. All of the statements related to a task are located in one place.

Prevent unexpected side effects by using private (local) variables that are not visible to other parts of the program.

Eliminate unnecessary repetition of code for frequently performed tasks.

Simplify debugging. Once the function works reliably, you can use it with confidence in many different situations.

If you know QuickPascal or QuickBasic, you will see many similarities in the C language. A C function serves the same basic purpose as a QuickPascal function or procedure or a QuickBasic FUNCTION or SUB procedure. In later sections, we'll note some differences between C and these languages.