Page 255 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 255
232 Chapter 8 Programming in C and C++
procedure can read data at the given address. A result can be returned from a procedure
using call by name, because the address of the result is passed into the procedure and the
procedure can write new data at the given address to pass data out of the procedure. Any
number of call by name input/output parameters can be used in a procedure.
A procedure may be used as a function that returns exactly one value and can be used
in the middle of algebraic expressions. The value returned by the function is put in a
return statement. For instance, the function power can be written
int power(int i, int j ) { int k, n;
for(n = 1, k = 0; k < j; k++) n = n * i;
return n;
}
This function can be called within an algebraic expression by a statement a=power(b,2).
The output of the function named in the return statement is passed by call by result.
In C, the address of a character string can be passed into a procedure, which uses a
pointer inside it to read the characters. For example, the string s is passed to a procedure
puts that outputs a string by outputting to the user's display screen one character at a
time using a procedure putchar. The procedure puts is written
void puts(s) char *s; {
while(*s != 0) putchar(*{s++));
>
It can be called in either of three ways, as shown side by side:
void main{) { void main() { void main() {
Char s[6]="ALPHA"; char s[6]="ALPHA"; puts{"ALPHA");
puts{&s[0]); puts(s); }
}
}
The first calling sequence, though permissible, is clumsy. The second is often used to
pass different strings to the procedure, while the third is better when the same constant
string is passed to the procedure in the statement of the calling program.
A prototype for a procedure can be used to tell the compiler how arguments are
passed to and from it. At the beginning of a program we write all prototypes, such as
extern void puts(char *);
The word extern indicates that the procedure puts( ) is not actually here but is
elsewhere. The procedure itself can be later in the same file or in another file. The
argument char * indicates that the procedure uses only one argument and it will be a
pointer to a character (i.e. the argument is called by name). In front of the procedure
name a type indicates the procedure's result. The type void indicates that the procedure
does not return a result. After the prototype has been declared, any calls to the procedure
will be checked to see if the types match. For instance, a call puts ( ' A' ) will cause an
error message because we have to send the address of a character (string), not a value of a
character to this procedure. The prototype for power () is:
extern int power{int, int);