Page 64 - Programming Microcontrollers in C
P. 64
Program Flow and Control 49
variables have been defined. In both cases, the branch is around op
erations of defining or deleting local variables. The alternative is to
make use of the setjmp() and longjmp() functions.
These handy library functions are declared in the setjmp.h
header file. Also declared in this header is a type called env. In your
program, you must define an external instance of env. This param
eter is used as an argument to setjmp(). setjmp() saves the
status of the computer in the instance of env when it is called. When
called originally setjmp()returns a zero or a FALSE. The func
tion longjmp() takes two arguments. The first is the env variable
corresponding to the return location in the program. The second is
an integer that is returned. Executation of the longjmp() returns
control to within the setjmp() function. When control is returned
to the function that called the setjmp() the parameter that was
passed from the longjmp() is returned. Therefore, when control
returns from setjmp() a simple test determines whether the func
tion setjmp() or longjmp() was called.
These functions restore the status of the computer to that which
existed when the setjmp() was called. This restoration automati
cally unrolls all function calls between the execution of the
setjmp() and the longjmp(). Also, there are no block or func
tion limits on the use of these functions. As long as env is a globally
accessible variable, longjmp() can pass control from any location
in a program to any other.
The Switch Statement
A second approach to selection between several alternates is the
switch statement. This approach is sometimes called the switch/case
statement. Following is a program that accomplishes exactly the same
as the above program. In this case, the switch statement is used.
/* Count the number of occurrences of each vowel
found in an input and also count all other charac
ters. */
#include <stdio.h>
int main(void)
{