C++ Lesson 8 – Operators | Dataplexa

Operators

In the last lesson you learned the types of values C++ can hold. Values alone are not enough β€” a program must do things with them: add them, compare them, combine them, and change them. Operators are the symbols that do this work. In this lesson you will learn the main families of operators, the rules that decide which one runs first, and the mistakes operators cause most often.

Arithmetic Operators β€” Doing Math

Arithmetic operators work on numbers, exactly as you would expect from school math. The one to watch is division: when both numbers are integers, C++ gives an integer answer and throws the fraction away.

OperatorMeaningExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33
%Remainder (modulo)10 % 31
#include <iostream>

int main() {
    int a = 10, b = 3;
    std::cout << "a + b = " << a + b << std::endl;
    std::cout << "a - b = " << a - b << std::endl;
    std::cout << "a * b = " << a * b << std::endl;
    std::cout << "a / b = " << a / b << std::endl;
    std::cout << "a % b = " << a % b << std::endl;
    return 0;
}
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1

a / b is 3, not 3.33, because both numbers are integers β€” remember Lesson 7. If either number were a double, the answer would keep its decimals. The remainder operator % gives what is left over after division: 10 divided by 3 is 3 remainder 1. It only works on integers, and it is the standard way to test whether a number is even β€” a number is even when n % 2 is 0.

Assignment and Compound Assignment

The plain assignment operator = stores a value in a variable. Compound assignment combines an operation with the assignment, so the code is shorter and the intent is clearer β€” and there is less chance of typing the variable name wrong on one side.

#include <iostream>

int main() {
    int score = 100;
    score += 10;   // score is now 110
    score -= 25;   // now 85
    score *= 2;    // now 170
    score /= 5;    // now 34
    score %= 7;    // now 6
    std::cout << "score = " << score << std::endl;
    return 0;
}
score = 6

Each line does the same as the longer form: score += 10 means exactly score = score + 10. Follow the value: 100 + 10 = 110, minus 25 = 85, doubled = 170, divided by 5 = 34, and 34 modulo 7 = 6 (because 7 goes into 34 four times, 28, leaving 6).

Increment and Decrement β€” ++ and --

Adding or subtracting exactly one is so common that C++ has a shortcut: ++ adds 1 and -- subtracts 1. There is a catch β€” it matters whether the operator comes before or after the variable.

#include <iostream>

int main() {
    int a = 5;
    int b = a++;   // b gets 5, then a becomes 6
    int c = ++a;   // a becomes 7, then c gets 7
    std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
    return 0;
}
a = 7, b = 5, c = 7

With a++ (postfix), the old value is used first and the variable is increased afterwards β€” so b gets 5. With ++a (prefix), the variable is increased first and the new value is used β€” so c gets 7. In a loop (Lesson 10) you will mostly write ++ on a line by itself, where the difference does not matter.

Comparison Operators β€” Asking Yes/No Questions

A comparison asks a question about two values and answers with a bool: true or false. These operators are the test in every if statement you will write, starting in the next lesson.

OperatorMeaningExample (age = 18)Result
==Equal toage == 18true
!=Not equal toage != 18false
<Less thanage < 18false
<=Less than or equal toage <= 18true
>Greater thanage > 18false
>=Greater than or equal toage >= 18true
#include <iostream>

int main() {
    int age = 18;
    std::cout << std::boolalpha;
    std::cout << "age == 18 : " << (age == 18) << std::endl;
    std::cout << "age >= 21 : " << (age >= 21) << std::endl;
    std::cout << "age != 0  : " << (age != 0) << std::endl;
    return 0;
}
age == 18 : true
age >= 21 : false
age != 0 : true

One warning that will save you hours of debugging: == compares, but a single = assigns. Writing if (age = 18) puts 18 into age and is always treated as true β€” the test never fails. Your compiler may warn you about it, but the best defense is to read your comparisons twice.

Logical Operators β€” Combining Conditions

Real decisions usually combine several conditions: old enough and holding a ticket, a child or a senior. The logical operators combine bool values into a new bool value.

OperatorMeaningResult
&&AND β€” both must be truetrue only when both sides are true
||OR β€” at least one must be truetrue when either side is true
!NOT β€” flips true to false and back!true is false, !false is true
ABA && BA || B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse
#include <iostream>

int main() {
    int age = 20;
    bool hasTicket = true;
    std::cout << std::boolalpha;
    std::cout << "Can enter: " << (age >= 18 && hasTicket) << std::endl;
    std::cout << "Is a child or a senior: " << (age < 13 || age >= 65) << std::endl;
    std::cout << "Not allowed: " << !(age >= 18) << std::endl;
    return 0;
}
Can enter: true
Is a child or a senior: false
Not allowed: false

A bonus for professionals: && and || are "short-circuit" operators. If the left side of && is false, the right side is never evaluated β€” and if the left side of || is true, the right side is skipped. Programs rely on this to skip tests that would be wrong or wasteful.

Operator Precedence β€” Who Goes First?

When an expression has several operators, precedence decides which runs first. You already know it from school: multiplication before addition. The full order, from highest to lowest, is:

PriorityOperators
Highest() parentheses
++ -- (postfix) and unary - !
* / %
+ -
< <= > >=
== !=
&&
||
Lowest= += -= and the other assignments
#include <iostream>

int main() {
    std::cout << "2 + 3 * 4 = " << 2 + 3 * 4 << std::endl;
    std::cout << "(2 + 3) * 4 = " << (2 + 3) * 4 << std::endl;
    std::cout << "10 - 4 / 2 = " << 10 - 4 / 2 << std::endl;
    return 0;
}
2 + 3 * 4 = 14
(2 + 3) * 4 = 20
10 - 4 / 2 = 8

2 + 3 * 4 is 14, because * runs before +. Parentheses always win, so (2 + 3) * 4 is 20 β€” when in doubt, add parentheses: they cost nothing and they make your intent obvious to the next reader. Operators on the same level run left to right, except assignment, which runs right to left β€” so a = b = 5 gives 5 to both.

Common Mistakes with Operators

Operators are small, so their mistakes are easy to make and hard to spot. If a result looks slightly wrong, check this list first.

MistakeWhat happensFix
Using = instead of ==Assigns instead of comparing, and the test is almost always trueRead every comparison twice, and let the compiler warnings help
Dividing two integers and expecting decimals10 / 3 is 3, not 3.33Make one number a double: 10.0 / 3
Using % on doublesThe remainder operator only works on integersUse fmod from <cmath>, or keep the values as integers
Forgetting precedencea + b * c is not (a + b) * cAdd parentheses to say what you mean
Comparing doubles with ==0.1 + 0.2 is not exactly 0.3 (Lesson 7)Check that the difference is very small instead

Practice β€” Write It Yourself

Try these in your editor. Compile and run each one before moving on.

  1. Read two numbers, then print their sum, difference, product, quotient as a double, and remainder.
  2. Read a number and print whether it is even, using n % 2 == 0.
  3. Start a counter at 5, then use ++ and -- in prefix and postfix form and print the counter after each step, so you can see the difference.
  4. Read an age and a bool "has ticket", and print whether the person can enter a concert β€” the rule is age >= 18 && hasTicket.

What does 10 % 3 give?


int a = 5; then int b = a++; What value is stored in b?


Which operator checks whether two values are equal?


Fill in the blanks β€” type the missing word into the box.

The operator that gives the remainder after division is .


To add 1 to a variable, write the operator after its name.


The operator that means AND, true only when both sides are true, is .