next up previous contents
Next: 練習題 Up: 運算子 Previous: Bitwise 運算子   Contents

Assignment 運算子

  1. 有以下的 Assignment 運算子:
    運算子 描述 例子
    = 將右邊的值設定給左邊的變數 C=A+B
    += 將右邊的值加到左邊的變數 C+=A, C=C+A
    -= 將左邊的變數減去右邊的值 C-=A, C=C-A
    *= 將左邊的變數乘以右邊的值 C*=A, C=C*A
    /= 將左邊的變數除以右邊的值 C/=A, C=C/A
    %= 左邊的變數為左邊變數除右邊變數取餘數 C%=A, C=C%A
    <<= 左邊變數 left shift 右邊值 C<<2, C=C<<2
    >>= 左邊變數 right shift 右邊值 C>>2, C=C>>2
    &= 左邊變數 bitwise AND 右邊值 C&=2, C=C&2
    ^= 左邊變數 bitwise exclusive OR 右邊值 C^=2, C=C^2
    |= 左邊變數 bitwise OR 右邊值 C|=2, C=C|2
  2. 程式範例
    #include <stdio.h>
    
    main()
    {
       int a = 21;
       int c ;
    
       c =  a;
       printf("Line 1 - =  Operator Example, Value of c = %d\n", c );
    
       c +=  a;
       printf("Line 2 - += Operator Example, Value of c = %d\n", c );
    
       c -=  a;
       printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
    
       c *=  a;
       printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
    
       c /=  a;
       printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
    
       c  = 200;
       c %=  a;
       printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
    
       c <<=  2;
       printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
    
       c >>=  2;
       printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
    
       c &=  2;
       printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
    
       c ^=  2;
       printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
    
       c |=  2;
       printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
    
    }
    



2015-01-16