Operators in C++

Operators in C++ are special symbols or keywords used to perform operations on variables and values. They are the building blocks of C++ programs and allow you to perform tasks like addition, subtraction, comparison, and more. C++ provides a wide range of operators to manipulate data, perform calculations, and control the flow of your programs. Understanding the various operators available in C++ is essential for anyone looking to become proficient in this programming language.

This tutorial is designed to provide a comprehensive understanding of C++ operators by categorizing them into different types and exploring their practical applications. Whether you are a beginner looking to grasp the fundamentals or an experienced developer seeking a quick reference, this guide will serve as a valuable resource for gaining insight into the world of operators in C++.

Types of Operators in C++

Operators in C++ can be categorized into several types based on their functionality. Here are the main categories of operators in C++:

  1. Arithmetic Operators:
  2. Arithmetic operators are used to perform arithmetic or mathematical operations such as addition, subtraction, multiplication or division, and more.

    There are two types of arithmetic operators: unary and binary. Unary operators are used to perform operations on a single operand (one value), while binary operators work with two operands (two values).

    Here's a table with examples of both unary and binary arithmetic operators in C++:

    OperatorTypeExampleDescription
    +
    Unary
    +7
    Unary plus, returns the positive value of the operand.
    -
    Unary
    -7Unary minus, negates the value of the operand.
    ++
    Unary
    x++Post-increment, returns the original value of x and then increments it.
    --
    Unary
    x--Post-decrement, returns the original value of y and then decrements it.
    ++
    Unary
    ++xPre-increment, increments x and then returns the new value.
    --
    Unary
    --xPre-decrement, decrements y and then returns the new value.
    +
    Binary
    a + bAddition, sums the values of  two operands.
    -
    Binary
    a - bSubtraction, subtracts second operand from the first.
    *
    Binary
    a * bMultiplication, multiplies two operands.
    /
    Binary
    a / bDivision, divides first operand by the second operand.
    %
    Binary
    a % bModulus, returns the remainder after the division of the first operand by the second operand.

    Here's a C++ program that demonstrates the use of both unary and binary arithmetic operators. It calculates various operations and displays the results, showing how these operators work in practice:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int x = 4;
        int y = 2;
    
        // Unary Operators
        cout << "Unary Operators:" << endl;
        cout << "+x is " << +x << endl;  // Unary plus
        cout << "-y is " << -y << endl;  // Unary minus
        cout << "Post-increment x++ is " << x++ << ", x becomes " << x << endl; // Post-increment
        cout << "Post-decrement y-- is " << y-- << ", y becomes " << y << endl; // Post-decrement
        cout << "Pre-increment ++x is " << ++x << ", x becomes " << x << endl;  // Pre-increment
        cout << "Pre-decrement --y is " << --y << ", y becomes " << y << endl;  // Pre-decrement
    
        // Binary Operators
        int a = 10;
        int b = 3;
        cout << "\nBinary Operators:" << endl;
        cout << "a + b is " << a + b << endl; // Addition
        cout << "a - b is " << a - b << endl; // Subtraction
        cout << "a * b is " << a * b << endl; // Multiplication
        cout << "a / b is " << a / b << endl; // Division
        cout << "a % b is " << a % b << endl; // Modulus
    
        return 0;
    }

    The output of the above code is as follows:

    Unary Operators:
    +x is 4
    -y is -2
    Post-increment x++ is 4, x becomes 5
    Post-decrement y-- is 2, y becomes 1
    Pre-increment ++x is 6, x becomes 6
    Pre-decrement --y is 0, y becomes 0
    
    Binary Operators:
    a + b is 13
    a - b is 7
    a * b is 30
    a / b is 3
    a % b is 1
  3. Assignment Operators:
  4. In C++, the assignment operator is denoted by the = symbol, and it is used to assign a value to a variable.

    The following table lists assignment operators in C++ with examples:

    OperatorNameExampleDescription
    =
    Assignment operator
    x = 40;
    Assigns the value on the right to the variable on the left. Assigns the value 40 to variable x
    +=
    Addition assignment operator
    x += 10;
    The value of the left variable is first added to the value of the right variable and then assigns the result to the left variable. Adds 10 to the current value of x.
    -=
    Subtraction assignment operator
    x -= 5;
    With the use of this operator, the value of the left variable is first subtracted with the value of the right variable and then assigns the result to the left variable. Subtracts 5 from the current value of x.
    *=
    Multiplication assignment operator
    x *= 3;
    With the use of this operator, the value of the left variable is first multiplied with the value of the right variable and then assigns the result to the left variable. Multiplies the current value of x by 3.
    /=
    Division assignment operator
    x /= 5;
    With the use of this operator, the value of the left variable is first divided by the value of the right variable and then assigns the result to the left variable. Divides the current value of x by 5.
    %=
    Modulus assignment operator
    x %= 2;
    Calculates the remainder of x divided by 2 and assigns it to x.

    Here's a C++ program that demonstrates the use of assignment operators. It calculates various operations and displays the results, showing how these operators work in practice:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        // Assignment Operator
        int a = 6;
        int b = 4;
        cout << "a is " << a << endl;
        cout << "b is " << b << endl;
    
        //  Add and Assignment Operator
        cout << "a += b is " << (a += b) << endl;
    
        // Subtract and Assignment Operator
        cout << "a -= b is " << (a -= b) << endl;
    
        //  Multiply and Assignment Operator
        cout << "a *= b is " << (a *= b) << endl;
    
        //  Divide and Assignment Operator
        cout << "a /= b is " << (a /= b) << endl;
    
        //  Modulus and Assignment Operator
        cout << "a %= b is " << (a %= b) << endl;
    
        return 0;
    }

    The output of the above code is as follows:

    a is 6
    b is 4
    a += b is 10
    a -= b is 6
    a *= b is 24
    a /= b is 6
    a %= b is 2
  5. Relational Operators:
  6. In C++, relational operators are used to compare two values or expressions and determine their relationship. These operators return a Boolean value (true or false) based on whether the comparison is true or false.

    Here's a table listing some of the relational operators in C++:

    OperatorNameExampleDescription
    ==
    Equal to
    x == y
    Checks if x is equal to y.
    !=
    Not equal to
    x != y
    Checks if x is not equal to y.
    <
    Less than
    x < y
    Checks if x is less than y.
    >
    Greater than
    x > y
    Checks if x is greater than y.
    <=
    Less than or equal
    x <= y
    Checks if x is less than or equal to y.
    >=
    Greater than or equal
    x >= y
    Checks if x is greater than or equal to y.

    Here's a program that demonstrates the use of relational operators in C++:

    #include <iostream>
    
    int main() {
        int x = 2;
        int y = 5;
    
        // Equal to (==)
        bool isEqual = (x == y); // false, as x is not equal to y
    
        // Not equal to (!=)
        bool isNotEqual = (x != y); // true, as x is not equal to y
    
        // Less than (<)
        bool isLessThan = (x < y); // true, as x is less than y
    
        // Greater than (>)
        bool isGreaterThan = (x > y); // false, as x is not greater than y
    
        // Less than or equal to (<=)
        bool isLessThanOrEqual = (x <= 4); // true, as x is equal to 4
    
        // Greater than or equal to (>=)
        bool isGreaterThanOrEqual = (y >= 8); // true, as y is equal to 8
    
        std::cout << "Is x equal to y? " << isEqual << std::endl;
        std::cout << "Is x not equal to y? " << isNotEqual << std::endl;
        std::cout << "Is x less than y? " << isLessThan << std::endl;
        std::cout << "Is x greater than y? " << isGreaterThan << std::endl;
        std::cout << "Is x less than or equal to 4? " << isLessThanOrEqual << std::endl;
        std::cout << "Is y greater than or equal to 8? " << isGreaterThanOrEqual << std::endl;
    
        return 0;
    }

    The output of the above code is as follows (1 represents true, while 0 represents false):

    Is x equal to y? 0
    Is x not equal to y? 1
    Is x less than y? 1
    Is x greater than y? 0
    Is x less than or equal to 4? 1
    Is y greater than or equal to 8? 0
  7. Logical Operators:
  8. Logical operators are used to check whether a condition is true or false. If the condition is true, it returns 1 whereas if the condition is false, it returns 0.

    Here's a table with some common logical operators in C++:

    OperatorNameExampleDescription
    &&
    Logical AND
    true && true returns true
    true && false returns false
    false && true returns false
    false && false returns false
    Returns true if both operands are true.
    ||
    Logical OR
    true || true returns true
    true || false returns true
    false || true returns true
    false || false returns false
    Returns true if at least one operand is true.
    !
    Logical NOT
    !true returns false
    !false returns true
    Returns true if the operand is false, and vice versa.

    Here's a program that demonstrates the use of logical operators in C++:

    #include <iostream>
    using namespace std;
    
    int main() {
        bool a = true;
        bool b = false;
    
        // Logical AND (&&) operator
        bool result_and = a && b; // false
        cout << "a && b is " << result_and << endl;
    
        // Logical OR (||) operator
        bool result_or = a || b; // true
        cout << "a || b is " << result_or << endl;
    
        // Logical NOT (!) operator
        bool result_not_a = !a; // false
        cout << "!a is " << result_not_a << endl;
    
        bool result_not_b = !b; // true
        cout << "!b is " << result_not_b << endl;
    
        return 0;
    }

    The output of the above code is as follows (1 represents true, while 0 represents false):

    a && b is 0
    a || b is 1
    !a is 0
    !b is 1
  9. Conditional (Ternary) Operator:
  10. In C++, the conditional operator, often referred to as the ternary operator, is a concise way to write conditional expressions. It provides a shorthand method for making decisions and choosing between two values based on a given condition.

    The ternary operator is represented by the ? : symbols and is structured as follows:

    condition ? expression_if_true : expression_if_false;

    Here's an explanation of each part of the above structure:

    • Condition: This is a boolean expression that is evaluated. If it is true, the value of the expression before the ? is returned; otherwise, the value after the : is returned.
    • Expression_if_true: This is the value or expression that is returned if the condition is true.
    • Expression_if_false: This is the value or expression that is returned if the condition is false.

    Here's a simple example that demonstrates the use of the ternary operator in C++:

    #include <iostream>
    using namespace std;
    
    int main() {
        int x = 4;
        int y = 8;
    
    int result = (x > y) ? x : y;
    cout << "result is " << result << endl;
    return 0;
    
    }

    In this example, (x > y) is the evaluated condition, checking if x is greater than y, which is false, resulting in the assignment of the value of y (which is 8) to the variable result.

    The output of the above code is as follows:

    result is 8
  11. Bitwise Operators:
  12. In C++, bitwise operators are used to perform operations at the binary level on integers. These operators work by manipulating the individual bits of the operands. Unlike traditional arithmetic operations such as addition, subtraction, and multiplication, which work on entire numbers, bitwise operations allow for faster processing by directly manipulating the bits.

    Here's a table with examples and explanations of bitwise operators in C++:

    OperatorNameExampleDescription
    &
    Bitwise AND
    5 & 3
    Compares each bit; result is 1 if both are 1.
    |
    Bitwise OR
    5 | 3
    Compares each bit; result is 1 if at least one is 1.
    ^
    Bitwise XOR
    5 ^ 3
    Compares each bit; result is 1 if bits are different.
    ~
    Bitwise NOT
    ~5
    Inverts all the bits; 0s become 1s and vice versa. 
    <<
    Left Shift
    5 << 2
    Shifts bits to the left, effectively multiplies by 2^2.
    >>
    Right Shift
    16 >> 2
    Shifts bits to the right, effectively divides by 2^2.

    Here are examples of each bitwise operator in C++:

    • Bitwise AND (&):
    • #include <iostream>
      using namespace std;
      
      int main() {
          int a = 5;          // Binary: 0101
          int b = 3;          // Binary: 0011
          int result = a & b; // Binary: 0001 (Decimal: 1)
          cout << "result is " << result << endl;
          return 0;
      }

      The output of the above code is as follows:

      result is 1
    • Bitwise OR (|):
    • #include <iostream>
      using namespace std;
      
      int main() {
          int a = 5;          // Binary: 0101
          int b = 3;          // Binary: 0011
          int result = a | b; // Binary: 0111 (Decimal: 7)
          cout << "result is " << result << endl;
          return 0;
      }

      The output of the above code is as follows:

      result is 7
    • Bitwise XOR (^):
    • #include <iostream>
      using namespace std;
      
      int main() {
          int a = 5;          // Binary: 0101
          int b = 3;          // Binary: 0011
          int result = a ^ b; // Binary: 0110 (Decimal: 6)
          cout << "result is " << result << endl;
          return 0;
      }

      The output of the above code is as follows:

      result is 6
    • Bitwise NOT (~)
    • #include <iostream>
      using namespace std;
      
      int main() {
          int a = 5;  // Binary: 0101
          int result = ~a;  // Binary: 1010 (Decimal: -6)
          cout << "result is " << result << endl;
          return 0;
      }

      The output of the above code is as follows:

      result is -6
    • Left Shift (<<):
    • #include <iostream>
      using namespace std;
      
      int main() {
          int a = 5;  // Binary: 0000 0101
          int result = a << 2;  // Binary: 0001 0100 (Decimal: 20)
          cout << "result is " << result << endl;
          return 0;
      }

      The output of the above code is as follows:

      result is 20
    • Right Shift (>>):
    • #include <iostream>
      using namespace std;
      
      int main() {
          int a = 16;  // Binary: 0001 0000
          int result = a >> 2;  // Binary: 0000 0100 (Decimal: 4)
          cout << "result is " << result << endl;
          return 0;
      }

      The output of the above code is as follows:

      result is 4
  13. Other Operators:
  14. Here is a list of other common operators available in C++:

    OperatorExampleDescription
    sizeof
    sizeof(int); //4
    Returns the size of the data type.
    &
    &num; //address of num
    Address-of Operator
    .
    studentObj.marks = 97;
    Member Access Operator
    ->
    ptr->marks = 97;
    It is used with pointers to access the class or variables.
    <<
    cout << 5;
    Output Stream Operator (Used for Printing)
    >>
    cin >> num;
    Input Stream Operator (Used for Getting Input)

    Here's an example that demonstrates the use of other common operators available in C++:

    #include <iostream>
    using namespace std;
    
    int main() {
        
        int num = 42;
        int x = 5, y = 3;
        string result;
    
        // sizeof operator
        cout << "Size of int: " << sizeof(int) << " bytes" << endl;
    
        // Address-of Operator
        cout << "Address of num: " << &num << endl;
    
        // Member Access Operator
        struct Student
        {
            int marks;
        };
        Student studentObj;
        studentObj.marks = 97;
        cout << "Marks: " << studentObj.marks << endl;
    
        // Member Access through Pointer
        Student *ptr = &studentObj;
        ptr->marks = 98;
        cout << "Updated Marks: " << studentObj.marks << endl;
    
        // Output Stream Operator
        cout << "Hello, World!" << endl;
    
        // Input Stream Operator
        int inputNum = 0; // Provide a default value
        cout << "Enter a number (or press Enter to use the default): ";
        cin >> inputNum;
        cout << "You entered: " << inputNum << endl;
    
        return 0;
    }

    The output of the above code is as follows:

    Size of int: 4 bytes
    Address of num: 0x61ff00
    Marks: 97
    Updated Marks: 98
    Hello, World!
    Enter a number (or press Enter to use the default): 5
    You entered: 5