Skip to content

Operators

Operator giúp tạo biểu thức từ biến và literal. Ưu tiên toán tử có thể gây bất ngờ, nên dùng ngoặc khi biểu thức dài. Bitwise operator rất hay dùng trong competitive programming.

int sum = a + b;
bool ok = x > 0 && x < 10;
int mask = 1 << bit;
GroupOperatorsExample
Arithmetic+ - * / %x % 2 == 0
Comparison== != < > <= >=a <= b
Logical`&&
Assignment= += -= *= /= %=x += 3
Bitwise&, &#124;, ^, ~, <<, >>mask & (1 << i)
Ternary?:x > 0 ? x : -x
int a = 10;
int b = 3;
int div = a / b; // 3
int mod = a % b; // 1
bool inside = a >= 1 && a <= 20;
int withBit = a | (1 << 2);
int sign = a >= 0 ? 1 : -1;
  • a / b với hai số nguyên sẽ trả về số nguyên.
  • && là logical AND, còn & là bitwise AND.
  • 1 << i overflow nếu i quá lớn với kiểu int.

operators toán tử arithmetic comparison logical assignment bitwise ternary and or shift modulo