Session 5 : Expression

4 Types of Expressions
- Arithmetic Evaluation
- Short-Circuit Evaluation
- Relational Evaluation
- Boolean Evaluation

Arithmetic Expressions
- Arithmetic evaluation was one of the motivations for the development of the first programming languages
- In programming language, arithmetic expressions consist of operators, operands, parentheses, and function calls
an operators can be :
1. Unary => meaning it has a single operand
2. Binary => meaning it has two operand
3. Ternary => meaning it has three operand
there's some operator rules in arithmetic expressions :
Operator Precedence Rules
   Typical precedence levels
- parentheses
- unary operators
- ** (if the language supports it)
- *, /
- +, -
Operator Associativity Rule
- The operator associativity rules for expression evaluation define the order in which adjacent operators with the same precedence level are evaluated
- Typical associativity rules
- Left to right, except **, which is right to left
- Sometimes unary operators associate right to left (e.g., in FORTRAN)
- APL is different; all operators have equal precedence and all operators associate right to left
- Precedence and associativity rules can be overriden with parentheses
Operand evaluation order
- Variables: fetch the value from memory
- Constants: sometimes a fetch from memory; sometimes the constant is in the machine language instruction
- Parenthesized expressions: evaluate all operands and operators first
- The most interesting case is when an operand is a function call
Potentials for Side Effects
- Functional side effects: when a function changes a two-way parameter or a non-local variable
- Problem with functional side effects:
When a function referenced in an expression alters another operand of the expression; e.g., for a parameter change:
        a = 10;
  /* assume that fun changes its parameter */
b = a + fun(&a); 

Relational and Boolean Expressions
Relational Expressions
- Use relational operators and operands of various types
- Evaluate to some Boolean representation
- Operator symbols used vary somewhat among languages (!=, /=, ~=, .NE., <>, #)
Boolean Expressions
- Operands are Boolean and the result is Boolean
- Example operators

Short Circuit Evaluation
=> An expression in which the result is determined without evaluating all of the operands and/or operators
- C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&& and ||), but also provide bitwise Boolean operators that are not short circuit (& and |)
- All logic operators in Ruby, Perl, ML, F#, and Python are short-circuit evaluated



Komentar