Operators in C++ Explained with Visuals

Operators in C++

Learn operators in C++, their types, and precedence, explained with real-world examples, visuals, and code snippets in our beginner-friendly guide.

Let’s first understand the concept of operators and operands in C++ with a real-world example illustrated below. The knife is actually the operator that executes the action of chopping the salad ingredients. The salad ingredients like tomato, lettuce, and cucumber are themselves operands. Thus, the knife (operator) is applied to the salad items (operands) to achieve the desired outcome (perform an operation).

Illustration of operands and operators in C++
Illustration of operands and operators in C++

Operators in C++

Operators are the symbols that perform operations on variables or values.

Operands in C++

An operator operates in operands. An operand can be a variable, value, or an expression on which the operation is performed.
For example:

  • 1 + 2
    • The numbers 1 and 2 are operands of the addition (+) operator.
  • a + b
    • Variable ‘a’ and variable ‘b’ are operands of the addition (+) operator.
  • 2 * a – 3 * b
    • The expressions ‘2a’ and ‘3b’ are operands for the subtraction (-) operator.

Types of Operators in C++

Based on the Number of Operands

1. Unary Operators:

Unary operators work with only one operand.

Example:

  • Increment (++): Increases the value of a variable by 1.
    • a++ increases the value of variable ‘a’ by 1.

2. Binary Operators:

Binary operators work with two operands.

Example:

  • Addition (+): Adds two values together.
    • a + b adds the values of variables ‘a’ and ‘b’.

3. Ternary Operators:

Ternary operators work with three operands.

Example:

  • Conditional (? :): Evaluates a condition and returns one of two possible values.
    • (a > b) ? a : b compares the values of variables ‘a’ and ‘b’. If ‘a’ is greater than ‘b’, it returns ‘a’; otherwise, it returns ‘b’.

Based on Functionality

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

OperatorDescriptionExample
+Adds two operandsa + b
Subtracts the second operand from the first a – b
*Multiplies two operandsa * b
/Divides the first operand by the seconda / b
%Computes the remainder of the divisiona % b
++Increments the value by 1a++
Decrements the value by 1a–
Arithmetic operators in C++

Here, note that the increment and decrement operators have two variations.

Prefix Increment/Decrement
  • Syntax: ++var, --var
  • Operation: The variable is incremented or decremented before its value is used in the expression.
  • Example: ++x; If x was 5, now x is 6.
Postfix Increment/Decrement
  • Syntax: var++, var--
  • Operation: The original value of the variable is used in the expression, and only then is the variable incremented or decremented.
  • Example: y = x++; If x was 5, y would become 5, and then x would become 6.

Example Code:

#include <iostream>
using namespace std;

int main() {
    int x = 5; // Initialize x with 5
    int y;     // Declare y for storing results

    // Demonstrating pre-increment
    y = ++x; // Increment x before assigning to y
    cout << "After pre-increment, y is: " << y << endl;
    cout << "Now, x is: " << x << endl;

    // Reset x to 5 for the next demonstration
    x = 5;

    // Demonstrating post-increment
    y = x++; // Assign x to y, then increment x
    cout << "After post-increment, y is: " << y << endl;
    cout << "Now, x is: " << x << endl;

    return 0;
}

Output:

After pre-increment, y is: 6
Now, x is: 6
After post-increment, y is: 5
Now, x is: 6

2. Assignment Operators

Assignment operators are used to assign values to variables.

OperatorDescriptionExample
Simple AssignmentAssigns the value of the right operand to the left operand.a = b assigns the value of variable b to variable a.
Compound AssignmentCombines arithmetic operations with assignment.a += b adds the value of variable b to variable a.

Example Code:

#include <iostream>
using namespace std;

int main() {
    int a = 5; // Simple assignment 
	int b = 10; 
	cout<<"a: "<<a<<" b: "<<b<<endl;
	a += b; // Compound assignment equivalent to a = a + b;
	cout<<"a after compound assignment: "<<a;

    return 0;
}

Output:

a: 5 b: 10
a after compound assignment: 15

3. Relational Operators

Relational operators are used to compare values. The result of comparison is always a binary value, either 1 (indicating true) or 0 (indicating false). Such operators are mostly used with if statements in decision-making.

OperatorNameExample
==Equal toa == b
!=Not equala != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b
Relational operators in C++

Example Code:

#include <iostream>
using namespace std;

int main() {
    int a = 10;
    int b = 20;

    cout<<"a = "<<a<<" b = "<<b<<endl;

    // Applying and printing the results of relational operators
    cout << "a == b: " << (a == b) << " (Is a equal to b?)" << endl;
    cout << "a != b: " << (a != b) << " (Is a not equal to b?)" << endl;
    cout << "a > b: " << (a > b) << " (Is a greater than b?)" << endl;
    cout << "a < b: " << (a < b) << " (Is a less than b?)" << endl;
    cout << "a >= b: " << (a >= b) << " (Is a greater than or equal to b?)" << endl;
    cout << "a <= b: " << (a <= b) << " (Is a less than or equal to b?)" << endl;

    return 0;
}

Output:

a = 10 b = 20
a == b: 0 (Is a equal to b?)
a != b: 1 (Is a not equal to b?)
a > b: 0 (Is a greater than b?)
a < b: 1 (Is a less than b?)
a >= b: 0 (Is a greater than or equal to b?)
a <= b: 1 (Is a less than or equal to b?)

4. Logical Operators

The logical operator combines multiple expressions together to check if they are evaluated as true or false. They are normally used with relational operators in an expression and perform operations on the results of the relational operators.

OperatorNameDescriptionExpressionOutput
&&Logical ANDReturns true if both operands are true3 > 1 && 5 < 2false
||Logical ORReturns true if either of its operands is true3 > 1 || 5 < 2true
!Logical NOTReverses the state of its operand.! (3>1)false
Logical operators in C++

Example:

#include <iostream>
using namespace std;

int main() {
    int a = 5;
    int b = 10;
    cout << " a = " << a << " b = " << b << endl;

    // Using logical operators combined with relational ones
    cout << " a != b: " << (a != b) << " - Is 'a' not equal to b?" <<endl; 
    cout << "(a < b) && (b > 5): " << ((a < b) && (b > 5)) << " - Is 'a' less than 'b' AND 'b' greater than 5?" << endl;
    cout << "(a == 5) || (b < 5): " << ((a == 5) || (b < 5)) << " - Is 'a' equal to 5 OR 'b' less than 5?" << endl;
    cout << "!(a == b): " << (!(a == b)) << " - Is 'a' NOT equal to 'b'?" << endl;
    cout << "(a != 5) && !(b <= a): " << ((a != 5) && !(b <= a)) << " - Is 'a' NOT equal to 5 AND 'b' NOT less than or equal to
    'a'?" << endl;

    return 0;
}

Output:

 a = 5 b = 10
 a != b: 1 - Is 'a' not equal to b?
(a < b) && (b > 5): 1 - Is 'a' less than 'b' AND 'b' greater than 5?
(a == 5) || (b < 5): 1 - Is 'a' equal to 5 OR 'b' less than 5?
!(a == b): 1 - Is 'a' NOT equal to 'b'?
(a != 5) && !(b <= a): 0 - Is 'a' NOT equal to 5 AND 'b' NOT less than or equal to 'a'?

5. Bitwise Operators

Bitwise operators performs operations at the bit level, manipulating individual bits of data. Operands are converted to bit-level before calculations are performed, which allows for faster processing compared to mathematical operations.

Examples:

NameSymbolDescriptionExample
Binary AND&Copies a bit to the evaluated result if it exists in both operands(2 & 3)
Binary OR|Copies a bit to the evaluated result if it exists in any of the operands(2 | 3)
Binary XOR^Copies the bit to the evaluated result if it is present in either of the operands but not both(2 ^ 3)
Left Shift<<Shifts the value to the left by the number of bits specified by the right operand(2 << 1)
Right Shift>>Shifts the value to the right by the number of bits specified by the right operand(2 >> 1)
One’s Complement~Changes binary digits 1 to 0 and 0 to 1(~3)

Precedence of Operators in C++

Imagine following a recipe to bake a cake. The recipe instructs you to mix the dry ingredients first before incorporating the wet ones. If you ignore this precedence and mix everything simultaneously, so the outcome (the cake) might not be what you expected. In this analogy, the order in which you combine ingredients (operations) significantly impacts the final product.

Illustration of precedence of operators in C++
Illustration of precedence of operators in C++


Similarly, in programming, the precedence of operators determines the order in which operations are performed, ensuring that expressions are evaluated correctly to produce the intended result.

The following table shows the priority of commonly used operators discussed in the article sorted from from highest to lowest in precedence. The operators that appear together have the same precedence.

PrecedenceOperatorDescription
1()Parenthesis
2++, -- (prefix)Prefix increment and decrement
3*, /, %Multiplication, Division, Remainder
4+, -Addition, Subtraction
5<, <=, >, >=Relational less than, less than or equal, greater than, greater than or equal
6==, !=Equality, Inequality
7!Logical NOT
8&&Logical AND
9||Logical OR
10++, -- (postfix)Postfix increment and decrement

Example Code:

#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 2;

    cout << "a = " << a << " b = " << b << endl;

    // Simple expression: Arithmetic operators
    cout << "Simple Arithmetic: a + b * 2 = " << a + b * 2 << endl;
    // Expected precedence: b * 2 is evaluated first, then added to a

    // Adding parentheses to change precedence
    cout << "With Parentheses: (a + b) * 2 = " << (a + b) * 2 << endl;
    // Parentheses force a + b to be evaluated first, then the result is multiplied by 2

    // More complex expression: Combination of relational and logical operators
    cout << "Complex Expression: (a > b) && (a + b < 10) = " << ((a > b) && (a + b < 10)) << endl;
    // Expected precedence: Relational operators are evaluated first, then the logical AND

    // Using a mix of operators to show precedence
    cout << "Mixed Operators: a + b > 3 && a - b < 10 = " << (a + b > 3 && a - b < 10) << endl;
    // Expected precedence: Arithmetic operations are performed first, followed by relational, then logical

    return 0;
}

Output:

a = 5 b = 2
Simple Arithmetic: a + b * 2 = 9
With Parentheses: (a + b) * 2 = 14
Complex Expression: (a > b) && (a + b < 10) = 1
Mixed Operators: a + b > 3 && a - b < 10 = 1

Now a practical code example that resonates with the analogy of the cake discussed in this article where the correct sequence leads to correct results due to the precedence of ingredients (operators ).

Take the example of the BMI calculator that calculates the BMI incorrectly when not using parentheses, which causes the division to happen first, then multiplication, due to operator precedence rules which state that when two more operators (/ and * in this case) have the same precedence, the expression is evaluated from left to right. When parentheses are added, they enforce the correct order of operations, squaring the height before dividing by the weight, leading to the correct BMI result.

Example Code:

#include <iostream>
using namespace std;

int main() {
    double weightInKilograms = 68; // Weight in kilograms
    double heightInMeters = 1.75;   // Height in meters

    // Incorrect calculation without proper use of parentheses
    // The division should have precedence over multiplication, but without parentheses, multiplication is done first
    double incorrectBMI = weightInKilograms / heightInMeters * heightInMeters; 
    cout << "Incorrect BMI (without parentheses): " << incorrectBMI << endl;

    // Correct calculation with the use of parentheses
    // Parentheses ensure that height is squared before division
    double correctBMI = weightInKilograms / (heightInMeters * heightInMeters); 
    cout << "Correct BMI (with parentheses): " << correctBMI << endl;

    return 0;
}

Output:

Incorrect BMI (without parentheses): 68
Correct BMI (with parentheses): 22.2041

Conclusion

Now that you have gained enough knowledge about operators, operands, their types, and precedence with simple code snippets. It’s time to practice with some interesting, and real-world programs from easy to complex problems in our next tutorial C++ practice programs on operators.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top