Skip to content

Chapter 4 of 31

Operators

Apply arithmetic, relational, logical, bitwise, assignment, and comparison operators.

30 minutes 10 quick checksBy Subha Prasad
Lesson 4 of 31Course navigation

Lesson content

Read, practise, then check your understanding

Arithmetic operators are +, -, *, /, and %. Integer division discards the fractional part; remainder works on integers. Relational operators compare values, logical operators combine conditions, and assignment operators update objects.

int total{17};
int groups{5};
int each = total / groups;      // 3
int left = total % groups;      // 2
bool valid = groups > 0 && each >= 0;
total += 3;

&& and || short-circuit, so the right operand may not run. This makes pointer != nullptr && pointer->ready() safe. Do not confuse logical operators with bitwise &, |, ^, ~, <<, and >>.

Bits and flags

#include <cstdint>

constexpr std::uint8_t read{1u << 0};
constexpr std::uint8_t write{1u << 1};
std::uint8_t permissions{read | write};
bool canWrite = (permissions & write) != 0;

Use unsigned types for deliberate bit manipulation. Shifts by an invalid count and signed overflow can produce undefined behavior.

Precedence is not documentation

Multiplication binds more tightly than addition, and assignment binds weakly, but parentheses communicate grouping better than memorized tables. Prefix ++i increments then yields the new value; postfix i++ yields the old value and may require a temporary. C++20’s <=> can synthesize consistent ordering operations for value types. Avoid expressions that modify and inspect the same value in confusing ways; split work into named steps.

Knowledge check

Answer every question correctly to complete this chapter.

What is 7 / 2 when both operands are int?
Which operator tests equality?
Which operator performs logical AND?
Which operator performs bitwise XOR?
What does the conditional operator use?
What does % compute for integers?
What does || guarantee when its left operand is true?
Which operator takes an address?
What is signed integer overflow?
What does <=> provide in C++20?

0 of 10 checks passed

Your progress is saved on this device.

Operators | C++ Lesson | Subha Prasad