CSC362 2004S, Class 34: Translating Conditionals Admin: * How much energy does it take to open an "automatic" door? * Honorable mention to Arjun and Oge in Modeling * Cool talk tonight at 4:15/4:30. * Picnic! * Nominate senior Math and CS majors for senior awards! * Regrouping on Friday * On grading Overview: * Perspectives on Boolean expression * Translating strict ifs * Translating short-circuit ifs * Translating case statements * On Booleans * Suppose code: test1 and test2 (test && test2) * Suppose test1 evaluates to false * Do you evalute test2? * No (Short-circuit evaluation): Stop evaluating as soon as you know result * Sometimes the successful evaluation of the second depends on the first holding * if (x >= 0) and (sqrt(x) < 100) ... * if ((p != null) && (p->x > 100)) * "Easier" for the programmer to write a series of nested if statements * Wastes computing resources to do the extra test * Easier for programmers in funky languages * Yes (Strict evaluation): Evaluate the whole expression no matter what * Permits parallel evaluation * Might rely on side effects * Easier to analyze/think about * The choice is an issue of language design * Short-circuit: C, Java, Scheme * Strict: Java (special notation), Pascal * The choice affects implementation Traditional internal representation of Booleans * 1: true;0: false To translate IF THEN 0 ELSE 1 1. Translate the expression: code_e, location_e 2. Translate the first statement: code_0 3. Translate the second statement: code_1 4. Generate three new labels. For convenience, I'll call them TRUEPART, FALSEPART, and ENDPART 5. Shove everything together code_e JumpIfZero location_e FALSEPART Jump TRUEPART TRUEPART: code_0 Jump ENDPART FALSEPART: code_1 Jump ENDPART ENDPART: Optimiziation will remove those jumps How do we evaluate the expression part? * Idea: Reserve memory locations for true (1) and false (0) true code: none location: the reserved location for true false code: none location: the reserved location for false Boolean variable code: none location: the location of the variable AND Get location for expression 0 and expression 1: loc_0, loc_1 Get code for expression 0 and expression 1: code_0, code_1 Create a new temp location, temp code: code_0 + code_1 + MULT loc_0 loc_1 -> temp location: 0 OR 1 Get location for expression 0 and expression 1: loc_0, loc_1 Get code for expression 0 and expression 1: code_0, code_1 Create a new temp location, temp code: code_0 code_1 BITWISEOR loc_0 loc_1 -> temp alternative code: code_0 code_1 JUMPNOTZERO loc_0 STORE_ONE JUMPNOTZERO loc_1 STORE_ONE MOVE 0 into temp JUMP END STORE_ONE: MOVE 1 into temp END: location: return temp NOT code: code_for_exp SUB 1 loc_of_exp loc_of_exp location: loc_of_exp x := 5; y := -5; if (x) println("x is true."); if (y) println("y is true."); if (x or y) println("both x and y are true");