Operators in C++

Topic 12 of 13

Welcome back to your C++ journey! In our previous lessons, we explored how to store data using variables and data types. But how do we actually do something with that data? This is where Operators come into play.

Whether you are calculating a grocery bill or building a complex game engine, operators are the tools that allow your code to perform actions and make decisions.

What is an Operator?

Definition: An operator is a symbol that tells the computer to perform a specific action or calculation on data.

The "Operand":

The data or variables that the operator works on, are called operands.

Explanation: Just like in mathematics or algebra, when you write, the symbol "+" is the operator, and the numbers "2" and "4" are the operands. In C++, these symbols act as instructions for the computer to process information and return a result.

Classifying Operators by "Operands"

Before looking at what operators do, we can group them by how many pieces of data they need to work:

  1. Unary Operators:

    These require only one operand. For example, the increment operator (++) simply adds one to a single variable.

  2. Binary Operators:

    These require two operands. Most common math symbols like + or - fall here because you can't subtract something from nothing (e.g., 8-1).

  3. Ternary (Conditional) Operators:

    These are unique because they require three operands to perform logic-based decisions.

The Main Types of C++ Operators

Arithmetic Operators

Definition: Symbols used for mathematical calculations.

The Big Five:

◦ + (Addition), - (Subtraction), * (Multiplication), / (Division).

The Modulus (%): This returns the remainder of a division. For example, results in (because 3 goes into 10 three times with 1 left over).

Daily Life Example: Think of a calculator app. Every time you press "plus" or "multiply," you are using arithmetic operators.

Assignment Operator (=)

Definition: Used to store a value in a variable.

Note: In C++, the single equal sign = does not mean "is equal to." It means "take the value on the right and put it in the box (variable) on the left."

Relational & Logical Operators

  • Relational:

    Used to compare two values

Operator Symbol Example
less than < 4<6
less than equal to <= x<=y
greater than > 100>20
greater then equals to >= x<=30
equals to == 5==5

 

  • Logical:

    Used to combine multiple conditions, let x and y are bool variables.

i.e. bool x=true, y=false;

Operator Symbol Example
AND && x&&y (false)
OR || x||y (true)
NOT ! !y (true)

 

Daily Life Example: A security system uses "Logical AND"—If the (A man is Armed) AND (The Door Opens), then trigger the siren.

Increment and Decrement Operators

  • Definition: Shortcuts to increase (++) or decrease (--) a value by exactly one.

For instance: x is an int typed variable, and initialized to 1, then:

x++ (x=x+1 //the value x is holding now is 2).

x—(x=x-1 //the value x is holding now is 1).

Understanding Precedence and Associativity

In C++, when you have a long expression like 2 + 3 * 5, the computer needs to know which part to do first. This is governed by two rules:

Precedence (Priority):

Some operators have higher priority. In C++, *, /, and % are calculated before + or -.

Associativity (Direction):

If two operators have the same priority (like * and /), C++ usually evaluates them from left to right.

Precedence  Operator Description Associativity
1 :: Scope resolution Left-to-right
2 a++, a--
type() type{}
a()
a[]
. ->
Postfix increment/decrement
Functional cast
Function call
Subscript
Member access
Left-to-right
3 ++a, --a
+a, -a
!, ~
(type)
*a, &a
sizeof
co_await
new, delete
Prefix increment/decrement
Unary plus/minus
Logical NOT, Bitwise NOT
C-style cast
Indirection, Address-of
Size-of
Await-expression (C++20)
Dynamic memory
Right-to-left
4 .*, ->* Pointer-to-member Left-to-right
5 *, /, % Multiplication, Division, Remainder Left-to-right
6 +, - Addition, Subtraction Left-to-right
7 <<, >> Bitwise shift Left-to-right
8 <=> Three-way comparison (C++20) Left-to-right
9 <, <=, >, >= Relational operators Left-to-right
10 ==, != Equality and Inequality Left-to-right
11 & Bitwise AND Left-to-right
12 ^ Bitwise XOR Left-to-right
13 | Bitwise OR Left-to-right
14 && Logical AND Left-to-right
15 || Logical OR Left-to-right
16 a?b:c
throw
co_yield
=, +=, -=, etc.
Ternary conditional
Throw operator
Yield expression (C++20)
Assignment operators
Right-to-left
17 , Comma operator Left-to-right

The "Bracket" Hack: If you want to change the order of calculation, use parentheses (). Anything inside brackets is solved first, allowing you to override the default rules.

 

Important: Integer Division Trap

One common mistake for beginners is dividing integers. In C++, if you divide two whole numbers (integers), the result will also be an integer.

  • Example: 4 / 10 will result in 0 in C++, because it discards the decimal part. To get 0.4, you would need to use float or double data types.

 

Try It Yourself! (Interactive Challenges)

Challenge 1: The Modulus Mission

  • Task: Predict the output of 17 % 5. Write a small code snippet to check if you were right!

Challenge 2: The Priority Puzzle

  • Task: Calculate the result of 10 + 5 * 2. Now, add brackets to make the addition happen first. How does the result change?

Reflection Prompt: Can you think of a situation in a video game where an Increment Operator (++) would be useful? (Hint: Think about scorekeeping or health points!)

Conclusion

Operators are the "verbs" of C++—they are how your program takes action. By mastering arithmetic, assignment, and the rules of precedence, you are well on your way to writing complex logic.

Join the Conversation: What is your biggest C++ fear? Is it the math, the syntax, or understanding the logic? Let’s talk in the comments!

For further reading, visit the Official C++ Documentation on Operators.