Page 244 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 244
8
Programming in C and C++
This chapter gives background material for Chapter 9, which shows how C or C++
statements are encoded in assembly language. Together, they illustrate what a
programmer is doing when he or she writes high-level language programs. However, if
you have already covered this material, it can be skipped.
The first section provides terminology and understanding of where to use high-level
language compilers and interpreters. We then begin with a description of C, illustrating
first operators and statements and then conditional and loop expressions. We give an
example of a program that uses many of the features we need in the next chapter, and
then discuss C++ and object-oriented programming.
8.1 Compilers and Interpreters
We first discuss the difference between an assembler and a compiler. A compiler is a
program that converts a sequence of (ASCII) characters that are written in a high-level
language into machine code or into assembly language that can be converted into
machine code. A high-level language is different from an assembly language in two
ways. First, a line of a high-level language statement will often generate five to a few
tens of machine instructions, whereas an assembly-language statement will usually
generate (at most) one machine instruction. Second, a high-level language is designed to
be oriented to the specification of the problem that is to be solved by the program and to
the human thought process, while a program in an assembly language is oriented to the
computer instruction set and to the hardware used to execute the program. Consider the
dot product subroutine used in the previous chapter, written in C below. Each line of the
program generates many machine instructions or lines of assembly-language code. Each
high-level language statement is designed to express an idea used in the statement of the
problem and is oriented to the user rather than the machine. The compiler could generate
the assembly-language program or the machine code produced by this program.
int dotprod(char v[], char w[] ) { int i, dprd = 0;
for(i = 0; i < 2; i++) dprd += v[i] * w[i];
return dprd;
}
221