Download View/Save - Global Specialties

Transcript
7.3. Functions
Functions are a key element in programming languages. In the previous chapters we already met and even used
functions, e.g. “writeString”, “writeInteger” and of course the main-function.
Functions are extremely useful for using identical program sequences at several locations of a program – the text
output functions used in previous chapters are good examples for this. Copying identical program code to all
locations where it is used would be very unhandy. Additionally, we would unnecessarily waste a lot of program
memory in doing something like this. Using one single function allows us to modify program modules at a single
central location instead of modifying a great number of copies. Using functions will simplify the program flow and
help us to keep the overview.
Therefore C allows us to combine program sequences to functions, which are always structured as follows:
<Return type> <Function
<Return type> <Function name> (<Parameter 1>, <Parameter 2>, ... <Parameter n>)
{
<Program>
}
Let's explain the idea in a small example with two simple functions and the alerady known mainfunction:
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void someLittleFunction(void)
{
writeString("[Function 1]\n");
}
void someOtherFunction(void)
{
writeString("[Function 2 – something different]\");
}
int main(void)
{
initRobotBase(); // Always start an Caterpillar-program by calling this function..
// A few function calls:
someLittleFunction();
someOtherFunction();
someLittleFunction();
someOtherFunction();
someOtherFunction();
return 0;
}
The program would display the following text at the output device:
[Function 1]
[Function 2 – something different]
[Function 1]
[Function 2 – something different]
[Function 2 – something different]
The main-function serves as the entry point and any C program will start by calling this function. Therefore each C
program MUST provide a main-function.