Slide 1Assignment OperatorsShort Hand AssignmentIncrement / Decrement OperatorsIncrement / Decrement Operators (cont.)Slide 6Slide 7Dale RobertsDepartment of Computer and Information Science,School of Science, IUPUIDale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected] 230Variable Declarations, Data types, Expressions - AssignmentsDale RobertsAssignment OperatorsAssignment OperatorsSyntax:Syntax:var = expression;Assign the value of expression to variable (var)Example:int x, y, z;x = 5;y = 7;z = x + y;int x, y, z;x = y = z = 0;int x = y = z = 0;int i, j;float f, g;i = f = 2.5;g = j = 3.5; i = 2; f = 2.5; g = 3.0; j = 3; Z = (x = 5) + (y = 7) much faster same as x = (y = (z = 0)); wrong ! int x = 0, y = 0, z = 0;Dale RobertsShort Hand AssignmentShort Hand AssignmentSyntaxSyntaxf = f op gf = f op g can be rewritten to be f op= gf op= gsuch as: a = a + 2 a += 2, a = a - 2 a -= 2, a = a * 2 a *= 2, a = a / 2 a /= 2, a = a % 2 a %= 2, a = a << 2 a <<= 2, a = a & 2 a &= 2, a = a | 2 a |= 2, a = a ^ 2 a ^= 2No blanks between op and = x *= y + 1 is actually x = x * (y+1) rather than x = x * y + 1Example: q = q / (q+2) q /= q+2j = j << 2 j <<= 2Advantage: help compiler to produce more efficient codeMore complicated examples:int a=1, b=2, c=3, x=4, y=5;a += b += c *= x + y - 6;printf(“%d %d %d %d\n”,a,b,c,x,y); a += 5 + b += c += 2 + x + y; a += 5 + (b+= c += 2 + x + y);/* result is 12 11 9 4 5 *//* wrong *//* result is 22 16 14 4 5 */Dale RobertsIncrement / Decrement OperatorsIncrement / Decrement Operators++++ (increment) (increment)-- -- (decrement)(decrement)Prefix OperatorPrefix OperatorBefore the variable, such as ++n or –nIncrements or decrements the variable before using the variablePostfix OperatorPostfix OperatorAfter the variable, such as n++ or n--Increments or decrements the variable after using the variable ++n1. Increment n 2. Get value of n in expression --n1. Decrement n 2. Get value of n in expression n++1. Get value of n in expression 2. Increment n n--1. Get value of n in expression 2. Decrement nDale RobertsIncrement / Decrement Operators Increment / Decrement Operators (cont.)(cont.)Simple casesSimple cases++i;i++;(i = i + 1; or i += 1;)--i;i--;(i = i - 1; or i -= 1;)Example:i = 5;i++; (or ++i;)printf(“%d”, i)i = 5;i--; (or --i;)printf(“%d”, i) 6 4Dale RobertsComplicated casesComplicated casesi = 5; i jj = 5 + ++i;i = 5;j = 5 + i++;i = 5;j = 5 + --i;i = 5;j = 5 + i--;6 116 104 94 10Dale RobertsIncrement / Decrement Operators Increment / Decrement Operators (cont.)(cont.)Invalid casesInvalid cases++3 3++ --3 3--++(x+y+z) (x+y+z)++ --(x+y+z)(x+y+z)--++x++ --x-- ++x-- --x++Note: Can not increment or decrement constant and expressioni ++j or i –-j (WRONG)i + ++j i + –-j i - --j i - ++j (OK)Example:i - - j (valid, second – is Unary - )i + + j (invalid, no +
View Full Document