C++‎ > ‎

運算子 operators

算術運算子 Arithmetic operators

 符號 功用 例 例
 + 加 i = j + k 3 = 1 + 2
 - 減 i = j - k 1 = 2 - 1
 * 乘 i = j * k 6 = 2 * 3
 / 除 i = j / k 0.3333... = 1 / 3
 % 取餘數 i = j % k    2 = 8 % 3

關係運算子 Relational and equality operators

 符號 比較 例 結果
 == 等於 2 == 2 true
 != 不等於 2 != 2 false
 > 大於 3 > 2 true
 < 小於 3 < 2 false
 >= 大於或等於 3 >= 3 true
 <= 小於或等於 3 <= 3 true

邏輯運算子 Logical operators

 符號 邏輯 例 結果
 && AND(且) true && false false
 || OR(或) true || false true
 ! NOT(非) !false true

位元運算子 Bitwise Operators

以二進位去做運算
  & | ^ ~
  AND OR XOR NOT
 a    b a & b a | b a ^ b ~a
 1    1 1 1 0 0
 1    0 0 1 1 0
 0    1 0 1 1 1
 0    0 0 1 0 1

移位運算子

右移: 20 >> 1 → 00010100 >> 1 → 00001010 = 10
左移: 20 << 1 → 00010100 << 1 → 00101000 = 40

類型轉換 Explicit type casting operator

int i;
float f = 3.14;
i = (int) f;

也可以寫成

i = int ( f );

sizeof()

回傳所佔用的位元組數 (bytes)

a = sizeof (char);


複合指定運算子 Combination assignment operator

 符號 說明 例
 = 指定 i = 2; → i=i+2
 += 加後指定 i += 2;
 -= 減後指定 i -= 2;
 *= 乘後指定 i *= 2;
 /= 除後指定 i /= 2;
 %= 餘後指定 i %= 2;
 ^= XOR後指定i ^= 2; 
 &= AND後指定 i &= 5;

遞增及遞減運算子 Increase and decrease

 符號 說明 例
 ++ 遞增 i++; → i=i+1
 -- 遞減 i--;

條件運算子 Conditional operator ( ? )

7==5 ? 4 : 3 //若7==5 return 4 否則return 3

運算子優先順序

 順序 運算子 方向
 1:: Left-to-right
 2++ -- (i++
() []
.
->
typeid()
const_cast
dynamic_cast
reinterpret_cast
static_cast
 
 3++ -- (++i
+ - (-1
! ~
(type)
*
&
sizeof
new, new[]
delete, delete[]
 Right-to-Left
 4.* ->* Left-to-right
 5* / % 
 6+ - 
 7<< >> 
 8< <=
> >=
 
 9== != 
 10& 
 11^ 
 12| 
 13&& 
 14|| 
 15? : Right-to-Left
 16
+= -=
*= /= %=
<<= >>=
&= ^= |=
 
 17throw 
 18, Left-to-right


Comments