Thursday, July 11, 2013

Objective-C > Operating Expression

  • Expression has precedence (優先次序).
  • Expression syntax:
 operand1;
 operand1 operator operand2;
 operand1? operand2: operand3;
  • Basic expression: +a, -a, a++/++a, a--/--a, ~a()
 int a = -3;                                           
 int b = +a;               // b = + (-3) = -3
 int c = -a;               // c = -(-3) = 3
 int a = 3;
 int b = ++a;              // b = 3 + 1 = 4
 int c = a++;              // c = a = 3
 int d = --a;              // d = 3 - 1 = 2
 int e = a--;              // e = a = 3
 BOOL a = YES;
 BOOL b = !a;              // b = NO
 BOOL c = !b;              // c = YES
  • Arithmetic operators: + , - , * , / , % (for 取餘數)
    • a
 int a = 11;
 int b = a + 33;           // b = 11 + 33 = 44
 int c = b - 22;           // c = 44 - 22 = 22
 int d = c *11;            // d = 22 x 11 = 242
 int e = d / 44;           // e = 242 / 44 = 5
 int f = e % 55;           // f = 5 %55 = 5 
  • Equity and relational operators: == , != , > , >= , < , <=
 int a = 11;
 int b = 22;

 BOOL c = a >= b;          // c = NO since c = 11 >= 22
 BOOL d = a <= b;          // d = YES since d = 11 <= 22
 BOOL e = c == d;          // e = NO since c = NO is not equal to d = YES

 BOOL f = a != b;          // f YES since a = 11 is not equal to b = 22
 BOOL f = (a != b);        // same as the above
  • Equal symbols: = , += , -= , /= , %= , <=
 int a = 11;

 a += 33;                  // a = a + 33 = 11 + 33 = 44
 a -= 22;                  // a = a - 22 = 44 - 22 = 22
 a *= 11;                  // a = a * 11 = 22 * 11 = 242
 a /= 44;                  // a = a / 44 = 242 / 44 = 5
 a %= 55;                  // a = a % 55 = 5 % 55 = 5        


<<Comma Operator (,)>>
  • Allows you to use two or more expressions where only one is expected
  • It evaluates the first operand (usually an expression), then discards the results
  • Then it evaluates the second operand and return the value
 a = (b = 3,  b  + 2)

No comments:

Post a Comment