Previous: 2.2.1 Comment Statements
Up: 2.2 Organization of C Programs - Simple Statements
Next: 2.2.3 Variable Declarations
Previous Page: 2.2.1 Comment Statements
To define a function in C, the programmer must specify two things: the function header, giving a name and other information about the function; and the function body, where the variables used in the function are defined and the statements which perform the steps of the function are specified.
In C, main() is the function that controls the execution of every program. The program starts executing with the first statement of main() and ends when main() ends. As we shall soon see, main() may call upon, i.e. use, other functions to perform subtasks.
The first line of any function is the function header which specifies the name of the function together with a parenthesized (possibly empty) argument list. In the above case, there is no argument list. We will discuss the concepts of arguments and argument lists in the next chapter.
The body of the function is contained within braces { and }. In C, a group of statements within braces is called a block which may contain zero or more statements and which may be nested, i.e. there may be blocks within blocks. A block is treated and executed as a single unit and is often called a compound statement. Such a compound statement may be used anywhere a statement can occur.
A program statement is like a sentence in English, except that it is terminated by a semi-colon. Statements within a block may be written in free form, i.e. words in programs may be separated by any amount of white space. (White space consists of spaces, tabs, or newlines (carriage returns)). Use of white space to separate statements and parts of a single statement makes programs more readable and therefore easier to understand.
The function body (as for any block) consists of two parts: variable declarations and a list of statements. Variable declarations will be described in more detail in the next section; however, all such declarations must occur at the beginning of the block. Once the first executable statement is encountered, no more declarations may occur for that block.
There are two types of statements used in our example (Figure 2.1); assignment statements and statements for printing information from the program. These will be discussed more below. The execution control flow proceeds sequentially in this program; when the function is executed, it begins with the first statement in the body and each statement is executed in succession. When the end of the block is reached, the function terminates. As we will soon see, certain control statements can alter this sequential control flow in well defined ways.