CS 228 lecture -*- Outline -*- * expressions (HR A.12) ** operators ------------------------ C++ OPERATORS OP EXAMPLE VALUE Unary: ! !(3==4) - - 3 ++ c++ -- c-- (cast) (int)4.2 Arithmetic: * 2 * 8 / 2 / 8 % 5 % 2 + 3 + 4 - 3 - 4 Shifting, I/O: << cout << 3 >> cin >> i Relational: < 3 < 4 <= 3 <= 4 > 3 > 4 >= 3 >= 4 == 3 == 4 != 3 != 4 ------------------------------ Result of relational op is 0 if false, 1 if true ----------------------------- Logical: && 3>7 && b || 3<7 || b Other: ? : (3<7) ? 3.5 : 7.1 = i = 3 += i += 3 ----------------------------- can use assignment operators with most arithmetic: -=, *=, ... ** parsing *** predecence In scheme give all parens, but in C++ can leave some out because of ... ----------------------------- OPERATOR PRECEDENCE 3 + 4 * 5 < 7 && 5 < - 9 def: higher precedence means ``binds more tightly''. ----------------------------- The above gives the precedence but have to group unaries: ! and - arith: * / % arith: + - shifting: << and >> relations: < <= >= and > equality: ==, != assignment ops.: =, +=, ... *** associativity ------------------------------ ASSOCIATIVITY 3 - 4 - 5 - - 3 a = b = c = 5 ------------------------------ all operators bind left to right, except for unary ops, conditional, and assignment, which bind right to left. *** exercises ------------------------------ FOR YOU TO DO Add parentheses to make the precedece and associativity obvious in: (a) 3 * 4 + 5 Answer: (3 * 4) + 5 (b) 3 - 4 / 5. / 6. (c) cout << 3 << 4 * 5 (d) cout << 3 << 4 == 5 ------------------------------ this last is probably a mistake, as << has higher precedence. can also discuss promotion for (b) ----------------------------- (e) 0 <= i && i < MAX (f) 0 <= i <= MAX ----------------------------- Moral: when in doubt, use parens; if you're reading code like these examples, look it up when in doubt. ** side-effects in expressions -------------------------- EXPRESSIONS WITH SIDE EFFECTS EXPRESSION VALUE EFFECT i = 2 a = b = c = 3 ------------------------- each assignment expression has both a value and a side-effect, this has value 3 and sets a, b, and c to 3. ------------------- c = c + 1 c += 1 ------------------- sets c to 4, then 5, values are 4 then 5 ------------------- ++c c++ c ------------------- sets c to 6, has value 6 value is 6, then sets c to 7