Presentation is loading. Please wait.

Presentation is loading. Please wait.

Expressions & Assignments

Similar presentations


Presentation on theme: "Expressions & Assignments"— Presentation transcript:

1 Expressions & Assignments
Imperative programming is based on the concept that the running program has a state – variables with values Program code will use assignment statements to alter those variables assignment statements often use expressions as their RHS expressions can be arithmetic boolean relational because of the reliance on arithmetic expressions, programming languages would inherit much from math conventions (variables, math operators, parens)

2 Continued Expressions consist of operands and operators
Three forms of operators Binary (2 operands, the standard form of mathematical operator) Unary (1 operand as in C’s i++ or in unary – as in -5) Ternary (3 operands, as in C’s conditional statement) Expressions requiring fetching the operator followed by operands, then applying the operator to those operands Design issues: what are the precedence and associativity rules? what order are operands evaluated? are there side effects? is operator-overloading available? what type mixing is allowed? Ruby is a pure OOPL so that a + b is not actually an expression but message passing. Here, we are passing the object a the message + with the parameter b. This convention was first pioneered in Smalltalk in 1980 and while it looks like any other language, the semantics are far different. In most languages, a + b becomes: load a into a register load b into a register add the registers But in Ruby/Smalltalk, this becomes follow pointer a to the object invoke the method for + passing a pointer to b perform the method + return a value

3 Operators Precedence FORTRAN C-languages Ada Ruby
Highest ** postfix ++, -- **, abs ** *, / prefix ++, -- *, /, mod, rem unary +, - +, unary +, unary +, *, /, % *, /, % binary +, binary +, - Lowest binary +, - “(” and “)” have the highest precedence in all languages it should also be noted that floating point arithmetic is not necessarily associative because of issues with precision a + b + c may not equal a + (b + c)

4 Associativity If two or more operators are of the same precedence, they are applied based on associativity all languages use left-to-right associativity except when dealing with exponent and unary operators in FORTRAN, exponent is the only right-to-left operator in Ada, a**b**c is illegal and so most be parenthesized in Ada, unary – has lower precedence than mod –a mod b is –(a mod b), not (-a) mod b in C-langauges, ++/-- and unary +/- are right associative and there is no exponent operator in VB, exponent (^) is left associative

5 Side Effects A side effect is when a function changes a parameter passed to it (or a global variable) This may lead to associativity not being maintained Example A + Fun(A) Fun(A) changes A to A+1 with left-to-right associativity, the sum is A + Fun(A), as expected with right-to-left associativity, the sum is A+1+ Fun(A) because A is changed to A+1 when Fun(A) executes Since A + Fun(A) should equal Fun(A) + A, the side effect would cause the language not to support associativity entirely Here is a side effect in C: int fun(int *x) { int temp = *x; *x = *x + 1; return temp * 2; } Here is another example: int a = 5; int fun1( ) { a = 17; return 3; void main ( ) { a = a + fun1( ); Assume fun2 changes its parameter value. Now consider d = a; result1 = (fun2(a) + b) / (fun2(a) – c); temp = fun2(d); result2 = (d + b) / (d - c) result1 should equal result 2, but do they?

6 More on Side Effects Side effects can occur when the parameter is passed by reference (a pointer) side effects are irrelevant if the language requires any function call be located at the end of an expression (but this limits you to 1 function call per expression) some languages disallow side effects parameters may only be passed by copy, not by reference and no global variables are permissible in the function Here is how some languages deal with side effects C/C++, Ada, Pascal side effects are allowed FORTRAN 77: expressions with function calls are legal only if the function does not change the value of any operands in the expression Java: operands evaluated left-to-right, programmer can avoid side effects by placing function calls to the right in an expression

7 Overload Operators Same operator is usable with different types
arithmetic operators (+, -, *, /) are all used for byte, short, int, long, float and double, so they are all overloaded implementation differs for each (or for many) overloading aids readability and writability overloading requires type checking + may also be used for and, union or string concatenation * is overloaded in C/C++ for pointer dereferencing & is overloaded in C/C++ to generate an address and bitwise AND compiler must choose the correct meaning of the operator given operand types Question: can the programmer overload an operator? available in Ada, C++, FORTRAN 95, Common Lisp, C# C++ restricts which operators can be overloaded (., .*, ::, ?:, sizeof)

8 Type Conversions Two dimensions of type conversions
explicit versus implicit conversion implicit conversions are called coercions and are usually initiated by the compiler Ada does not do implicit coercions, so the assignment below is not legal since * cannot apply to both an integer and a float A : Integer; B, C : Float; C = A * B; in C-languages, an explicit conversion is called a cast is the conversion increasing or decreasing precision? narrowing – going from a larger type to smaller type (e.g. int to short int) narrowing is rarely safe widening – going from a smaller type to larger widening is almost always safe however, consider going from a 32-bit int to a 32-bit float while this is thought of as widening, you might lose precision!

9 Relational and Boolean Expressions
Evaluate to True/False relational operators always have lower precedence than arithmetic so that the relational comparison is performed after any arithmetic operations (ex. a+1 > b-2) boolean operators usually have lower precedence than relational operators except possibly NOT FORTRAN abbreviations originated because early keypunches did not have <, > symbols available FORTRAN 95 continued to use the abbreviations, but also included = =, <>, <, >, <=, >= JavaScript/PHP add = = = and != = for non-coercible comparison Operation Ada C/Java FORTRAN77 Equal = = = EQ. Not equal /= != NE. Greater Than > > GT. Less Than < < LT. Greater/Equal >= >= GE. Less/Equal <= <= LE. AND and && AND. OR or | | OR. NOT not ! NOT. The === and !== operators in JavaScript and PHP are interesting. “7” == 7 is true because JavaScript will coerce the int value 7 into a String to match the left-hand side type. But === disables coercion and so “7”===7 is false. Ruby has the same idea but implements the two operators as == (coercion available) and eql? (no coercion). It should be noted that in OOPLs, == means that the two variables point to the same object in memory, not that the two objects store the same values. So, in Java: String s1=“Frank”, s2=“Frank”; s1==s2 is false. We would have to use a String method (e.g., equals) to determine if the Strings have equivalent values.

10 Example expressions In FORTRAN: In Ada In C: a > b > c
A+B .GT. 2 * C . AND. K .NE. 0 order of operations: *, +, GT, NE, AND In Ada A > B and A < C or K=0 is illegal because and/or have equal precedence and therefore must parenthesize, the proper expression is (A > B and A < C) or K = 0 with order of precedence as <, > and = performed first in a left-to-right order, followed by and followed by or In C: a > b > c is legal as a > b returns a 1 or 0 which is then compared to c C-language operator precedence postfix++,-- prefix ++, --, ! unary +, - *, /, % binary +, - <, >, <=, >= = =, != && | |

11 Short Circuiting A short circuited evaluation of an expression occurs if the result can be determined without evaluating the entire expression (13 * A) * (B / 13 - C) if A=0, expression evaluates to 0, right term (B / …) is ignored (A >= 0) and (B < 10) if A < 0, right side ignored since entire expression is false We take advantage of short circuiting to simplify code to avoid errors while(ptr!=NULL && ptr->value > target) ptr = ptr->next; without short circuiting, we either risk an error arising or we have to separate this into a while loop (ptr!=NULL) with an if statement inside it (ptr->value > target)

12 Short Circuiting in Various Languages
In Ada, short-circuiting is available using AND THEN and OR ELSE While (Index <= Listlen) and then (List[index] /= key) do In Modula-2, Turbo Pascal, AND and OR are short-circuited this is not true of Standard Pascal In C, C++, Java, && and || are short circuited, & and | are not one must be cautious in C-languages when using short circuiting, consider this: (a > b) && ((b++) / 3) if a > b is false, the right side of the expression is not performed and so b remains unchanged!

13 The Assignment Statement
Syntactic form: <target_var> <ass_op> <expr> In order to differentiate assignment and equality, two different operators are used FORTRAN, BASIC, PL/I, C, C++, Java, C#, Python all use = for <ass_op> Ada/Algol/Pascal/Modula all use := in F#, you must precede any assignment with the word let as in let x = 0 In PL/I, = is used for both assignment and equality this leads to the instruction A = B = C being difficult to understand unlike in C where it does B = C and then A = B, this sets A equal to the boolean expression B = C if B = C then A is set to true, otherwise false The multiple assignment operators aid writability and damage readability.

14 Compound Assignments Starting in C, languages began offering the ability to do multiple assignments in one statement C offers three forms: a = b + (c = d / b) – 1 assigns c to d / b, then assigns a to b + c – 1 prefix/postfix incr/decr can be placed in an expression as in a = b++; which differs from a = ++b; a = b = c (b = c; a = b; ) You can also do assignment in conditions as in while((c = getchar)!=‘\n’) And C-like languages have short-cut operators +=, -=, etc

15 In Other Languages PL/I Python Common Lisp Perl
SUM, TOTAL = 0 Python a, b, c = <expr1>, <expr2>, <expr3> Common Lisp (setf a b c d) same as a=b, c=d Perl ($a, $b, $c) = (1, 2, 3); C-languages also have the conditional statement of the form flag ? count1 : count2 = 0


Download ppt "Expressions & Assignments"

Similar presentations


Ads by Google