Because an expression parser evaluates an algebraic expression, it is important that you understand the constituent parts of an expression. 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 +, −, /, *, ^, %, and =
Parentheses
Variables
Here, the caret operator (^) indicates exponentiation (not the XOR as it does in C#), and the equal sign (=) 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
Assume this precedence for each operator:
Highest | + − (unary) |
^ | |
* / % | |
+ − | |
Lowest | = |
Operators of equal precedence evaluate from left to right.
The parser developed in this chapter will be subject to a few constraints. First, all variables are single letters (in other words, 26 variables, A through Z, are available). The variables are not case-sensitive (a and A are treated as the same variable). Second, all numeric values are assumed to be double, although you could easily modify the parser to handle other types of values. Finally, to keep the logic clear and easy to understand, only rudimentary error checking is included.