Expressions. McGraw-Hill The Complete Reference Fourth Edition
Reklamë
Reklamë
964
C + + : T h e C o m p l e t e R e f e r e n c e
W hile Standard C++ is quite extensive, there are still a few things that it does not provide. In this chapter we will examine one of them: the expression parser.
An expression parser is used to evaluate an algebraic expression, such as
(10 – 8) * 3. Expression parsers are quite useful and are applicable to a wide range of applications. They are also one of programming's more elusive entities. For various reasons, the procedures used to create an expression parser are not widely taught or disseminated. Indeed, many otherwise accomplished programmers are mystified by the process of expression parsing.
Expression parsing is actually very straightforward, and in many ways easier than other programming tasks. The reason for this is that the task is well defined and works according to the strict rules of algebra. This chapter will develop what is commonly referred to as a recursive-descent parser and all the necessary support routines that enable you to evaluate numeric expressions. Three versions of the parser will be created. The first two are nongeneric versions. The final one is generic and may be applied to any numeric type. However, before any parser can be developed, a brief overview of expressions and parsing is necessary.
Expressions
Since an expression parser evaluates an algebraic expression, it is important to understand what the constituent parts of an expression are. Although expressions can be made up of all types of information, this chapter deals only with numeric expressions. For our purposes, numeric expressions are composed of the following items:
■ Numbers
■ The operators +, −, /, *, ^, %, =
■ Parentheses
■ Variables
For our parser, the operator ^ indicates exponentiation (not the XOR as it does in C++), and = is the assignment operator. These items can be combined in expressions according to the rules of algebra. Here are some examples:
10 – 8
(100 – 5) * 14/6 a + b – c
10^5 a = 10 – b
Shkarko
Reklamë