In C++ programming, operators are fundamental tools for processing data and logical judgment. They are like symbols in mathematical formulas, helping us perform calculations and comparisons on variables and constants. This section will start with the most basic arithmetic, comparison, and logical operators, explaining these core syntaxes in a simple and understandable way for beginners.
一、什么是运算符?¶
Operators are symbols that tell the compiler to perform specific operations on data. For example, + is the addition operator, and == is the equality comparison operator. C++ provides various types of operators. We will first learn the three most commonly used categories: arithmetic operators (for numerical calculations), comparison operators (for judging size relationships), and logical operators (for combining conditional judgments).
二、算术运算符¶
Arithmetic operators are used to perform basic operations such as addition, subtraction, multiplication, and division on numerical values. The main types include:
1. Basic Arithmetic Operators¶
| Operator | Name | Function | Example (assuming a=5, b=3) | Result |
|---|---|---|---|---|
+ |
Addition | Add two numbers | a + b |
8 |
- |
Subtraction | Subtract the second number from the first | a - b |
2 |
* |
Multiplication | Multiply two numbers | a * b |
15 |
/ |
Division | Divide the first number by the second | a / b |
1 |
% |
Modulus | Remainder after dividing the first number by the second | a % b |
2 |
Notes:
- Division (/): If both operands are integers (e.g., 5/2), the result truncates the decimal part (only the integer part is kept). If there is a floating-point number (e.g., 5.0/2), the result retains the decimal (resulting in 2.5).
- Modulus (%): Only applicable to integers. The result is the remainder after the “integer part of the quotient” (the sign of the remainder matches the dividend). For example: -5 % 3 = -2, 5 % -3 = 2.
2. Increment/Decrement Operators (++、–)¶
Increment (++) and decrement (--) are special arithmetic operators that add 1 or subtract 1 to a variable’s value. They have two usage forms: “prefix” and “postfix”, differing in whether to operate first or after use:
-
Prefix ++: Increment the variable first, then use its value.
Syntax:++variable
Example:int a = 1; ++a;→abecomes 2, and the value used is 2. -
Postfix ++: Use the variable’s current value first, then increment.
Syntax:variable++
Example:int a = 1; int b = a++;→bfirst takes the current value ofa(1), thenabecomes 2.
Example Comparison:
int x = 3;
int y = ++x; // Prefix ++: x increments to 4 first, then y takes x's value (4)
cout << "x=" << x << ", y=" << y << endl; // Output: x=4, y=4
int m = 3;
int n = m++; // Postfix ++: n takes m's current value (3) first, then m increments to 4
cout << "m=" << m << ", n=" << n << endl; // Output: m=4, n=3
三、比较运算符¶
Comparison operators are used to judge the relationship between two values. The result is a boolean value (true or false), commonly used in conditional judgments (e.g., if statements). The main types include:
| Operator | Name | Function | Example (assuming a=5, b=3) | Result |
|---|---|---|---|---|
== |
Equality | Check if two values are equal | a == b |
false |
!= |
Inequality | Check if two values are not equal | a != b |
true |
> |
Greater than | Check if the left value is greater than the right | a > b |
true |
< |
Less than | Check if the left value is less than the right | a < b |
false |
>= |
Greater than or equal to | Check if the left value is greater than or equal to the right | a >= b |
true |
<= |
Less than or equal to | Check if the left value is less than or equal to the right | a <= b |
false |
Notes:
- Comparison operators return boolean values (true or false), which can be output using cout (actual output is 1 or 0, but bool types are interpreted as true/false).
- Do not confuse the assignment operator = with the equality comparison ==: = is for assignment (e.g., a = 5), while == checks for equality (e.g., a == 5).
Example:
int a = 5, b = 5;
bool equal = (a == b); // true (5 equals 5)
bool notEqual = (a != b); // false (5 does not equal 5? No, a and b are both 5, so false)
bool greater = (a > b); // false (5 is not greater than 5)
cout << "equal=" << equal << ", notEqual=" << notEqual << endl; // Output: equal=1, notEqual=0
四、逻辑运算符¶
Logical operators are used to combine multiple conditions for logical judgments of “AND”, “OR”, and “NOT”, with results still being true or false.
1. Logical AND (&&)¶
- Function: Returns
trueonly if both conditions aretrue; otherwise, returnsfalse. - Short-circuiting: If the left condition is
false, the right condition is not executed (saves computation resources).
Example:
bool result = (3 > 1) && (5 > 2); // true && true → true
bool result2 = (3 < 1) && (5 > 2); // false && true → false
2. Logical OR (||)¶
- Function: Returns
trueif at least one condition istrue; returnsfalseonly if both arefalse. - Short-circuiting: If the left condition is
true, the right condition is not executed.
Example:
bool result = (3 > 1) || (5 < 2); // true || false → true
bool result2 = (3 < 1) || (5 < 2); // false || false → false
3. Logical NOT (!)¶
- Function: Inverts the condition:
truebecomesfalse, andfalsebecomestrue.
Example:
bool result = !(3 > 1); // !true → false
bool result2 = !(5 == 5); // !false → true
Combined Logical Operator Example¶
int age = 18;
bool isAdult = (age >= 18) && (age <= 60); // true (18 years old and not over 60)
bool isStudentOrAdult = (age < 18) || (age >= 60); // false (18 is neither a student nor an elderly person)
bool isNotAdult = !(age >= 18); // false (18 is an adult)
cout << "isAdult=" << isAdult << ", isStudentOrAdult=" << isStudentOrAdult << endl;
五、总结¶
Operators are foundational tools in C++ programming. Mastering arithmetic, comparison, and logical operators is critical for subsequent learning:
- Arithmetic operators: For numerical calculations. Key points: // (integer division truncates decimals), % (modulus only for integers), and the difference between prefix and postfix ++/--.
- Comparison operators: Return boolean values to judge size relationships. Note the difference between == (equality comparison) and = (assignment).
- Logical operators: For combining conditions. && (AND) and || (OR) have short-circuiting properties; ! (NOT) is for negation.
By understanding these examples and practicing more (e.g., modifying values in examples to observe results), beginners can quickly grasp these basic syntaxes.
Output of the example in the original text:
isAdult=1, isStudentOrAdult=0