Back to series
· 10 min read

Operators & Expressions


1. What Is an Operator?

An operator is a symbol or keyword in a programming language used to perform a specific operation.

For example:

a = 10
b = 5

result = a + b

Here:

  • + is an operator.
  • a and b are operands (Operand).
  • a + b is an expression.
  • The result of the operation is 15.

The core role of an operator is to define the behavior of an operation, for example:

  • Numeric computation
  • Comparison
  • Logical operations
  • Bit operations
  • Assignment
  • Member access
  • Type checking

1.1 The Composition of an Operator

An operator expression usually consists of operators and operands.

For example:

result = a + b * c

Where:

Element Meaning
a, b, c Operands
+, * Operators
b * c Subexpression
a + b * c Complete expression

Operators can be classified by the number of operands they take:

Type Meaning Example
Unary operator Operates on one operand -a, !a
Binary operator Operates on two operands a + b, a == b
Ternary operator Selects an expression based on a condition a ? b : c

Note that the symbols and behavior of operators are defined by the specific programming language. The same symbol may have different semantics in different languages.

2. What Is an Expression?

An expression is a code structure composed of elements such as literals, variables, operators, and function calls, which can be evaluated according to the rules of the language.

For example:

10 + 20

This is an expression, and its evaluation result is 30.

Another example:

age >= 18

This is a comparison expression, and its evaluation result is a boolean value.

An expression can be very simple, or it can be composed of multiple nested subexpressions.

total = price * quantity + shipping_fee

Where:

  • price * quantity is a subexpression.
  • price * quantity + shipping_fee is the complete expression.
  • total = ... is an assignment statement.

2.1 The Difference Between Expressions and Statements

Expressions and statements are two different syntactic concepts.

An expression is usually used to compute and produce a value, while a statement is used to organize the execution behavior of a program.

For example, in Python:

a + b

This is an expression.

result = a + b

This is an assignment statement, which contains the expression a + b.

if a > b:
    print(a)

This is a conditional statement, in which a > b is a conditional expression.

The differences between the two:

Aspect Expression Statement
English Expression Statement
Main purpose Computes and produces a value Expresses the program's execution structure
Can it be nested Usually yes Depends on the language syntax
Example a + b if, while, assignment statements
Does it always produce a value Usually has an evaluation result Not necessarily

Different languages do not draw exactly the same line between expressions and statements.

For example, an assignment statement in Python is not itself an ordinary expression, whereas an assignment expression in JavaScript can produce the assigned value.

2.2 The Composition of an Expression

An expression can usually contain:

  • Literals
  • Variables
  • Operators
  • Function calls
  • Property access
  • Array or object access
  • Other subexpressions

For example:

const result = user.score * 2 + calculateBonus();

It can be broken down into:

flowchart TB
    A["Full expression"] --> B["user.score * 2"]
    A --> C["calculateBonus()"]
    B --> D["Property access user.score"]
    B --> E["Multiplication operation"]
    A --> F["Addition operation"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

3. Arithmetic Operators

Arithmetic operators are used to perform numeric calculations and are the most common type of operator.

3.1 Basic Arithmetic Operators

Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 Depends on the language
% Remainder 10 % 3 1
** Exponentiation 2 ** 3 8

Note that different languages have different rules for division and remainder.

For example, Python:

print(10 / 3)   # 3.3333333333333335
print(10 // 3)  # 3
print(10 % 3)   # 1

Python uses / for true division and // for floor division.

Java:

System.out.println(10 / 3);    // 3
System.out.println(10.0 / 3);  // 3.3333333333333335

In Java, dividing two integers still yields an integer; the fractional part is truncated.

3.2 Integer Division and Floating-Point Division

Integer division and floating-point division are a common source of errors.

For example:

int a = 10;
int b = 3;

double result = a / b;
System.out.println(result);

The result is:

3.0

The reason is:

  1. a and b are both integers.
  2. a / b first performs integer division.
  3. Integer division yields 3.
  4. The result is then converted to double, yielding 3.0.

If you want a floating-point result, you need to convert an operand before the operation:

double result = (double) a / b;

The result is:

3.3333333333333335

The timing of type conversion directly affects the result of an expression.

3.3 Remainder Operation

The remainder operation is typically used to obtain the remainder after division.

For example:

print(10 % 3)  # 1

Common uses of the remainder operation:

  • Determining odd/even numbers
  • Loop indices
  • Time conversion
  • Periodic calculations
  • Hash algorithms

For example, determining odd/even numbers:

number = 10

if number % 2 == 0:
    print("偶数")
else:
    print("奇数")

It should be noted that when negative numbers are involved in a modulo operation, different languages may adopt different rules.

Python:

print(-7 % 3)  # 2

Java:

System.out.println(-7 % 3); // -1

In Python, the sign of the modulo result is related to the divisor; in Java, the sign of the remainder is related to the dividend.

Therefore, when handling negative-number modulo across languages, you cannot assume the results will be completely consistent.

IV. Relational Operators

Relational operators are used to compare the relationship between two operands.

They usually return a boolean result.

Operator Meaning Example
== equal to a == b
!= not equal to a != b
> greater than a > b
< less than a < b
>= greater than or equal to a >= b
<= less than or equal to a <= b

For example:

age = 20

print(age >= 18)  # True
print(age == 20)  # True
print(age < 18)   # False

4.1 Equality Comparison vs. Reference Comparison

In some languages, it is necessary to distinguish between comparing whether the values of two objects are equal and comparing whether two references point to the same object.

Java:

String a = new String("hello");
String b = new String("hello");

System.out.println(a == b);      // false
System.out.println(a.equals(b)); // true

Here:

  • For reference types, == compares reference identity, i.e., whether they point to the same object.
  • equals() is inherited from Object by default, but String overrides it to compare string contents.

Python:

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)  # True
print(a is b)  # False

Here:

  • == compares whether the values of the objects are equal.
  • is compares whether two names point to the same object.

This shows that equality comparison and object identity comparison are two different concepts.

4.2 Floating-Point Comparison

Due to precision limitations, directly comparing computed results of floating-point numbers with the equality operator may cause problems.

For example:

a = 0.1 + 0.2
b = 0.3

print(a == b)  # False

In actual development, it is usually necessary to set a tolerance according to the business precision requirements:

a = 0.1 + 0.2
b = 0.3

epsilon = 1e-9

print(abs(a - b) < epsilon)

For data of different orders of magnitude, a fixed absolute error may not be sufficient, and relative error also needs to be considered.

V. Logical Operators

Logical operators are used to combine or invert boolean conditions.

Common logical operations include:

Operation Python Java / C JavaScript
Logical AND and && &&
Logical OR or || ||
Logical NOT not ! !

5.1 Logical AND (AND)

The result is true only when all conditions hold.

A B A AND B
True True True
True False False
False True False
False False False

For example:

age = 25
is_member = True

result = age >= 18 and is_member

The result is true only if the age requirement is met and the person is a member.

5.2 Logical OR (OR)

As long as one condition is true, the result is true.

A B A OR B
True True True
True False True
False True True
False False False

For example:

is_admin = False
is_owner = True

result = is_admin or is_owner

Either an administrator or the resource owner can satisfy the access condition.

5.3 Logical NOT (NOT)

Logical NOT is used to invert a Boolean value.

A NOT A
True False
False True

For example:

is_login = False

if not is_login:
    print("请先登录")

5.4 Short-Circuit Evaluation

Short-circuit evaluation is a very important execution mechanism in logical operations.

When the result of a logical expression can already be determined, the runtime may stop evaluating the remaining operands.

For common short-circuit logical operations:

  • A && B: When A is false, B is not evaluated.
  • A || B: When A is true, B is not evaluated.

For example, in JavaScript:

let user = null;

if (user && user.name) {
    console.log(user.name);
}

When user is null, the result of user && user.name is already determined, and user.name will not be accessed.

Short-circuit evaluation flow:

flowchart TD
    A["Start evaluating the logical expression"] --> B["Evaluate left operand"]
    B --> C{"Can the result be determined"}
    C -->|"Yes"| D["Return current result"]
    C -->|"No"| E["Evaluate right operand"]
    E --> F["Get final result"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Short-circuit evaluation not only improves efficiency but is also often used to guard expressions that may throw exceptions.

For example:

if user is not None and user.name == "Alice":
    print("匹配成功")

First check whether user is None, then access its attribute.

Note that not all logical operators use short-circuit evaluation. Some languages also provide non-short-circuit logical operations or bitwise operation forms.

6. Assignment Operators

Assignment operators are used to assign a value to a variable or to update the data currently associated with the variable.

6.1 Basic Assignment

age = 25
name = "Alice"

= represents assignment, not an equality check in the mathematical sense.

For example:

x = 10
x = x + 5

The second line means:

  1. Read the current value of x.
  2. Compute x + 5.
  3. Assign the result back to x.

The final value of x is 15.

6.2 Compound Assignment Operators

Compound assignment combines an operation with assignment.

Operator Equivalent Form
+= a = a + b
-= a = a - b
*= a = a * b
/= a = a / b
%= a = a % b
&= a = a & b
|= a = a \| b
^= a = a ^ b
<<= a = a << b
>>= a = a >> b

For example:

count = 10
count += 5

print(count)  # 15

Note that compound assignment is not necessarily exactly equivalent to the expanded expression in all languages.

For example, in Python:

a = [1, 2]
a += [3]

This usually extends the list in place.

Whereas:

a = [1, 2]
a = a + [3]

creates a new list object and rebinds a.

For types with overloaded operators or custom assignment behavior, this distinction may be even more pronounced.

6.3 Increment and Decrement Operators

Languages such as C, C++, Java, and JavaScript provide:

  • ++: increment.
  • --: decrement.

For example:

int count = 10;

count++;
count--;

Increment and decrement also have prefix and postfix forms.

int a = 10;

int x = ++a;
int y = a++;

Differences:

Expression Behavior
++a Increment first, then use the result
a++ Use the original value first, then increment

Execution process:

flowchart TD
    A["Variable a = 10"] --> B["Execute ++a"]
    B --> C["a becomes 11"]
    C --> D["Expression result is 11"]
    D --> E["Execute a++"]
    E --> F["Expression result is 11"]
    F --> G["a becomes 12"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Python does not support ++ and -- as increment and decrement operators.

7. Bitwise Operators

Bitwise operators operate directly on the binary bits of integers.

Bitwise operations are very common in low-level development, network protocols, permission control, graphics computation, and performance optimization.

7.1 Bitwise AND

Operator: &

The result is 1 only when both corresponding binary bits are 1.

  0101
& 0011
------
  0001

For example:

print(5 & 3)  # 1

7.2 Bitwise OR

Operator: |

If either corresponding bit is 1, the result is 1.

  0101
| 0011
------
  0111
print(5 | 3)  # 7

7.3 Bitwise XOR

Operator: ^

The result is 1 when the two corresponding bits differ, and 0 when they are the same.

  0101
^ 0011
------
  0110
print(5 ^ 3)  # 6

7.4 Bitwise NOT

Operator: ~

Inverts the binary bits of an integer.

In Python:

print(~5)  # -6

Python integers use arbitrary-precision signed integer semantics, so ~5 cannot simply be understood as a fixed 8-bit or 32-bit two's complement inversion.

For Python integers:

\sim x = -x-1

7.5 Left Shift and Right Shift

Operator Meaning
<< Left shift
>> Right shift

For example:

print(5 << 1)  # 10
print(8 >> 1)  # 4

Binary illustration:

5  = 0101
5 << 1 = 1010 = 10

8  = 1000
8 >> 1 = 0100 = 4

For non-negative integers, shifting left by one bit is usually equivalent to multiplying by 2, and shifting right by one bit is usually equivalent to dividing by 2 and rounding down.

However, this is not a mathematical rule that can be applied directly in all cases:

  • Left shift may cause integer overflow.
  • Signed right shift may involve sign extension.
  • Logical right shift and arithmetic right shift behave differently.
  • The shift count and operand types are constrained by the language specification.

7.6 Practical Uses of Bitwise Operations

Permission Control

Different binary bits can be used to represent different permissions.

READ = 1       # 0001
WRITE = 2      # 0010
EXECUTE = 4    # 0100

permissions = READ | WRITE

print(permissions & READ)  # 1

Determining Odd or Even

number = 10

if number & 1:
    print("奇数")
else:
    print("偶数")

Checking Whether a Bit Is Set

flags = 0b1010
mask = 0b0010

if flags & mask:
    print("目标标志位已设置")

8. Conditional Operator (Ternary Operator)

The conditional operator is used to choose between different expression results based on a condition.

Common form:

condition ? expression1 : expression2

For example, in JavaScript:

const age = 20;

const result = age >= 18 ? "成年人" : "未成年人";

When the condition is true, it returns the result of the first expression; otherwise, it returns the result of the second expression.

Some languages use different syntax.

Python:

age = 20

result = "成年人" if age >= 18 else "未成年人"

Conditional expressions can simplify simple branching logic.

However, if conditions are nested too much, readability decreases:

const result = score >= 90
    ? "优秀"
    : score >= 60
        ? "及格"
        : "不及格";

Complex logic is usually better handled with if, else, or other branching structures.

9. Other Common Operators

In addition to the operators above, different programming languages also provide many operators for special purposes.

9.1 Member Access Operator

Used to access object properties or struct members.

For example:

user.name

Here, . is used to access the name property of the user object.

C language:

user.age

If accessing a member through a struct pointer:

user_ptr->age

9.2 Array and Index Access Operators

Access elements in an array or collection by index.

numbers = [10, 20, 30]

print(numbers[0])  # 10

Here, [] is used for index access.

9.3 Function Call Operator

Use parentheses to call a function.

result = calculate(10, 20)

Here, () indicates a function call.

9.4 Type Checking Operators

Used to determine the type of an object or expression.

JavaScript:

console.log(typeof "hello"); // string
console.log(typeof 123);     // number

Java:

if (obj instanceof String) {
    System.out.println("字符串");
}

Python:

isinstance(123, int)

9.5 Nullish Coalescing Operator

JavaScript provides ??, used to use the default value on the right when the left operand is null or undefined.

const username = inputName ?? "Guest";

Unlike logical OR ||, ?? does not treat 0, false, and the empty string as nullish values that need to be replaced.