C++ Basics: Fundamental Operations

C++ provides a rich set of operators to manipulate data, which can be broadly categorized into the following types:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Assignment Operators
  5. Increment and Decrement Operators
  6. Other Operators (bitwise operations, comma operator, <span>sizeof</span>, etc., which will be briefly mentioned in this article)

1. Arithmetic Operators

Used to perform basic mathematical operations.

Operator Description Example Result (assuming <span>a=10</span>, <span>b=3</span>)
<span>+</span> Addition <span>a + b</span> <span>13</span>
<span>-</span> Subtraction <span>a - b</span> <span>7</span>
<span>*</span> Multiplication <span>a * b</span> <span>30</span>
<span>/</span> Division <span>a / b</span> <span>3</span> (integer division)
<span>%</span> Modulus (remainder) <span>a % b</span> <span>1</span> (10 divided by 3 gives a remainder of 1)
<span>-</span> Unary Negation <span>-a</span> <span>-10</span>

Key Details:

  • Division Operator <span>/</span>:

    • When both operands are integers, it performs integer division, discarding the decimal part and keeping only the integer part.
      int result1 = 10 / 4;  // result1 is 2, not 2.5
      
    • If at least one operand is a floating-point number, it performs floating-point division, retaining the decimal.
      double result2 = 10.0 / 4; // result2 is 2.5
      double result3 = 10 / 4.0; // result3 is 2.5
      
  • Modulus Operator <span>%</span>:

    • Calculates the remainder of two integers.
    • Very Important: Both operands must be of integer type.
    • The sign of the result is the same as the dividend (the left operand).
      int result4 = 10 % 3;  // result4 = 1
      int result5 = -10 % 3; // result5 = -1
      int result6 = 10 % -3; // result6 = 1 (in most compilers)
      // double result7 = 10.5 % 3; // Error! Cannot use % with floating-point numbers
      
    • Common uses: checking for even/odd <span>(x % 2 == 0)</span>, limiting number ranges <span>(x % 60)</span>, etc.

2. Relational Operators

Used to compare the size relationship between two values, returning a boolean value <span>true</span> (true, usually 1) or <span>false</span> (false, usually 0). Commonly used in <span>if</span> statements and loop conditions.

Operator Description Example Result (assuming <span>a=10</span>, <span>b=20</span>)
<span>==</span> Equal to <span>a == b</span> <span>false</span>
<span>!=</span> Not equal to <span>a != b</span> <span>true</span>
<span>></span> Greater than <span>a > b</span> <span>false</span>
<span><</span> Less than <span>a < b</span> <span>true</span>
<span>>=</span> Greater than or equal to <span>a >= b</span> <span>false</span>
<span><=</span> Less than or equal to <span>a <= b</span> <span>true</span>

Note:

  • Do not confuse assignment <span>=</span> with comparison <span>==</span>, this is one of the most common mistakes made by beginners.
    int x = 5;
    if (x = 10) { // Error! This assigns 10 to x, and the assignment operation returns true, so the condition is always true
        // This code will always execute
    }
    if (x == 10) { // Correct! This compares if x is equal to 10
        // This code will not execute because x is 5
    }
    

3. Logical Operators

Used to connect multiple conditions, returning <span>true</span> or <span>false</span> based on boolean logic (AND, OR, NOT).

Operator Description Example Meaning
<span>!</span> Logical NOT <span>!a</span> If <span>a</span> is false, then <span>!a</span> is true; and vice versa.
<span>&&</span> Logical AND <span>a && b</span> Only when both <span>a</span> and <span>b</span> are true, the result is true.
<span>||</span> Logical OR <span>a || b</span> If either <span>a</span> or <span>b</span> is true, the result is true.

Key Details: Short-Circuit Evaluation

This is an extremely important feature of logical operations.

  • <span>&&</span> (Logical AND) Short-Circuit: If the first operand is <span>false</span>, then the entire expression is definitely <span>false</span>, and the second operand will not be evaluated.
    int a = 0;
    if (a != 0 &amp;&amp; (10 / a) &gt; 1) { // Since a != 0 is false, (10 / a) will not be evaluated, avoiding division by zero error!
        // ...
    }
    
  • <span>||</span> (Logical OR) Short-Circuit: If the first operand is <span>true</span>, then the entire expression is definitely <span>true</span>, and the second operand will not be evaluated.
    int x = 10;
    if (x == 10 || (++x &gt; 10)) { // Since x == 10 is true, the ++x operation will not be executed!
        cout &lt;&lt; x &lt;&lt; endl; // Output is still 10, not 11
    }
    

4. Assignment Operators

Used to assign values to variables.

Operator Example Equivalent to
<span>=</span> <span>a = b</span> <span>a = b</span>
<span>+=</span> <span>a += b</span> <span>a = a + b</span>
<span>-=</span> <span>a -= b</span> <span>a = a - b</span>
<span>*=</span> <span>a *= b</span> <span>a = a * b</span>
<span>/=</span> <span>a /= b</span> <span>a = a / b</span>
<span>%=</span> <span>a %= b</span> <span>a = a % b</span>

Compound assignment operators (like <span>+=</span>, <span>-=</span>) are more concise and can sometimes produce more efficient code.

5. Increment and Decrement Operators

Used to increase or decrease the value of a variable by 1, very commonly used.

Operator Description Example Effect
<span>++</span> Increment <span>a++</span> or <span>++a</span> <span>a = a + 1</span>
<span>--</span> Decrement <span>a--</span> or <span>--a</span> <span>a = a - 1</span>

Key Details: Difference Between Prefix and Postfix

  • Prefix (<span>++a</span>, <span>--a</span>): Increment/Decrement first, then use. First, perform the increment or decrement operation on the variable, then use the new value in the expression.

    int a = 5;
    int b = ++a; // 1. a is incremented to 6; 2. Then a(6) is assigned to b. Result: a=6, b=6
    
  • Postfix (<span>a++</span>, <span>a--</span>): Use first, then increment/decrement. First, use the current value of the variable in the expression, then perform the increment or decrement operation on the variable.

    int a = 5;
    int b = a++; // 1. First, the current value of a(5) is assigned to b; 2. Then a is incremented to 6. Result: a=6, b=5
    

Advice: In standalone statements (like <span>a++;</span> or <span>for</span> loop’s <span>i++</span>), both have the same effect and can be used interchangeably. However, in complex expressions, be very careful to avoid undefined behavior (like <span>a = a++;</span>) and hard-to-understand code.

6. Brief Introduction to Other Operators

  • Bitwise Operators: Directly operate on the binary bits of integers in memory.
    • <span>&</span> (bitwise AND), <span>|</span> (bitwise OR), <span>^</span> (bitwise XOR), <span>~</span> (bitwise NOT), <span><<</span> (left shift), <span>>></span> (right shift).
    • Commonly used in low-level programming, device drivers, and optimization.
  • Conditional Operator (Ternary Operator): <span>? :</span>
    • Format: <span>condition ? expression1 : expression2</span>
    • If the condition is true, the value of the entire expression is the value of expression1; otherwise, it is the value of expression2.
    • <span>int max = (a > b) ? a : b; // Get the larger value between a and b</span>
  • Comma Operator: <span>,</span>
    • Executes multiple expressions in order, and the value of the entire comma expression is the value of the last expression.
    • <span>int x = (a = 5, b = 10, a + b); // x is 15</span>
  • <span>sizeof</span> Operator:
    • Returns the number of bytes occupied by a type or object in memory.
    • <span>cout << sizeof(int); // Outputs 4 (on most systems)</span>

Comprehensive Example

#include &lt;iostream&gt;
using namespace std;

int main() {
    // 1. Arithmetic Operations
    int a = 20, b = 6;
    cout &lt;&lt; "a / b = " &lt;&lt; (a / b) &lt;&lt; endl;   // Outputs 3 (integer division)
    cout &lt;&lt; "a % b = " &lt;&lt; (a % b) &lt;&lt; endl;   // Outputs 2

    double c = 20.0;
    cout &lt;&lt; "c / b = " &lt;&lt; (c / b) &lt;&lt; endl;   // Outputs 3.33333 (floating-point division)

    // 2. Relational and Logical Operations
    int age = 18;
    bool hasTicket = true;
    if (age &gt;= 18 &amp;&amp; hasTicket) {
        cout &lt;&lt; "You can enter the cinema." &lt;&lt; endl;
    }

    // 3. Increment and Decrement
    int x = 5, y;
    y = x++; // y = 5, then x becomes 6
    cout &lt;&lt; "x: " &lt;&lt; x &lt;&lt; ", y: " &lt;&lt; y &lt;&lt; endl;

    y = ++x; // x becomes 7, then y = 7
    cout &lt;&lt; "x: " &lt;&lt; x &lt;&lt; ", y: " &lt;&lt; y &lt;&lt; endl;

    // 4. Compound Assignment
    int count = 10;
    count += 5; // count = count + 5;
    cout &lt;&lt; "Count: " &lt;&lt; count &lt;&lt; endl; // Outputs 15

    return 0;
}

Summary and Recommendations

  1. Precedence and Associativity: When there are multiple operators in an expression, follow the rules of operator precedence and associativity to determine the order of operations. If you can’t remember, use parentheses <span>()</span> to clearly specify the order of calculations, which is both clear and safe.
  2. Beware of Confusion: Always be cautious of the confusion between <span>=</span> and <span>==</span>.
  3. Understand Integer Division: This is a common point of confusion for beginners.
  4. Make Good Use of Short-Circuit Evaluation: It can improve efficiency and prevent certain errors (like division by zero).
  5. Be Cautious with Increment/Decrement: When using prefix or postfix in complex expressions, be very clear about the differences.

C++ Basics: Fundamental Operations

C++ Basics: Fundamental Operations

  • Detailed introduction to the National Youth Informatics Olympiad competition system

  • What are the benefits of participating in the Informatics Olympiad for children?

  • National Youth Informatics Olympiad competition system: Detailed introduction to CSP-J

  • National Youth Informatics Olympiad competition system: Detailed introduction to CSP – S

  • National Youth Informatics Olympiad competition system: Detailed introduction to NOIP

  • Ranking of difficulty levels in the Informatics Olympiad

Leave a Comment