C++ Programming
Operators and Expressions
Mastering operators and expressions concepts and implementation.
On this page
Operators and Expressions
Operators are symbols that perform operations on variables and values. Expressions combine variables, operators, and values to produce results.
What are Operators?
Operators are special symbols that tell the compiler to perform specific mathematical, logical, or relational operations.
Expressions are combinations of operators, variables, and values that evaluate to a single value.
Types of Operators
1. Arithmetic Operators
Perform mathematical operations.
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 3 * 4 | 12 |
/ | Division | 15 / 3 | 5 |
% | Modulus (remainder) | 10 % 3 | 1 |
Example:
1int a = 10, b = 3;
2int sum = a + b; // 13
3int diff = a - b; // 7
4int product = a * b; // 30
5int quotient = a / b; // 3 (integer division)
6int remainder = a % b; // 1
Important Notes:
- Integer division truncates (drops decimal part)
- Modulus only works with integers
- Division by zero causes runtime error
2. Assignment Operators
Assign values to variables.
| Operator | Example | Equivalent To |
|---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 2 | x = x - 2 |
*= | x *= 4 | x = x * 4 |
/= | x /= 2 | x = x / 2 |
%= | x %= 3 | x = x % 3 |
Example:
1int x = 10;
2x += 5; // x is now 15
3x -= 3; // x is now 12
4x *= 2; // x is now 24
5x /= 4; // x is now 6
3. Increment and Decrement Operators
Increase or decrease value by 1.
| Operator | Name | Effect |
|---|---|---|
++x | Pre-increment | Increment first, then use |
x++ | Post-increment | Use first, then increment |
--x | Pre-decrement | Decrement first, then use |
x-- | Post-decrement | Use first, then decrement |
Example:
1int a = 5;
2int b = ++a; // a becomes 6, b becomes 6
3int c = a++; // c becomes 6, a becomes 7
4
5int x = 10;
6int y = --x; // x becomes 9, y becomes 9
7int z = x--; // z becomes 9, x becomes 8
4. Relational Operators
Compare two values and return true or false.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
> | Greater than | 5 > 3 | true |
< | Less than | 5 < 3 | false |
>= | Greater than or equal | 5 >= 5 | true |
<= | Less than or equal | 5 <= 3 | false |
Example:
1int age = 20;
2bool isAdult = age >= 18; // true
3bool isTeen = age < 18; // false
4bool isExactly20 = age == 20; // true
5. Logical Operators
Combine boolean expressions.
| Operator | Name | Description | Example | ||||
|---|---|---|---|---|---|---|---|
&& | AND | Both must be true | true && false = false | ||||
| ` | ` | OR | At least one true | `true | false = true` | ||
! | NOT | Reverses boolean | !true = false |
Truth Tables:
AND (&&):
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
OR (||):
| A | B | A | B | |
|---|---|---|---|---|
| true | true | true | ||
| true | false | true | ||
| false | true | true | ||
| false | false | false |
NOT (!):
| A | !A |
|---|---|
| true | false |
| false | true |
Example:
1int age = 20;
2bool hasLicense = true;
3bool canDrive = age >= 18 && hasLicense; // true
4
5int score = 85;
6bool passed = score >= 60 || score == 100; // true
7
8bool isWeekend = false;
9bool isWorkday = !isWeekend; // true
6. Bitwise Operators
Operate on individual bits (advanced topic).
| Operator | Operation | Example | ||
|---|---|---|---|---|
& | AND | 5 & 3 = 1 | ||
| ` | ` | OR | `5 | 3 = 7` |
^ | XOR | 5 ^ 3 = 6 | ||
~ | NOT | ~5 | ||
<< | Left shift | 5 << 1 = 10 | ||
>> | Right shift | 5 >> 1 = 2 |
7. Conditional (Ternary) Operator
Shorthand for if-else statements.
Syntax: condition ? value_if_true : value_if_false
Example:
1int age = 20;
2string status = (age >= 18) ? "Adult" : "Minor";
3// status is "Adult"
4
5int max = (a > b) ? a : b; // Returns larger value
Operator Precedence
Operators are evaluated in a specific order when multiple operators appear in an expression.
Order (highest to lowest):
- Parentheses
() - Unary operators (
++,--,!,-) - Multiplicative (
*,/,%) - Additive (
+,-) - Relational (
<,>,<=,>=) - Equality (
==,!=) - Logical AND (
&&) - Logical OR (
||) - Assignment (
=,+=, etc.)
Example:
1int result = 2 + 3 * 4; // 14 (not 20!)
2int result2 = (2 + 3) * 4; // 20
3bool check = 5 > 3 && 2 < 4; // true
Best Practice: Use parentheses to make precedence clear, even when not necessary.
Type Conversions in Expressions
When different types are used in expressions, C++ performs automatic conversions.
Rules:
- Smaller types are promoted to larger types
int+double→doublechar+int→int
Example:
1int a = 5;
2double b = 3.5;
3double result = a + b; // a is converted to double, result is 8.5
Common Expressions
Mathematical Expressions
1double area = 3.14159 * radius * radius; // Circle area
2double celsius = (fahrenheit - 32) * 5.0 / 9.0; // Temperature conversion
Boolean Expressions
1bool isValid = age >= 18 && age <= 65;
2bool isWeekend = day == 6 || day == 7;
3bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
String Concatenation
1string firstName = "John";
2string lastName = "Doe";
3string fullName = firstName + " " + lastName; // "John Doe"
Best Practices
- ✅ Use parentheses for clarity, even when not needed
- ✅ Avoid complex expressions - break into multiple statements
- ✅ Be careful with integer division - use
doubleif you need decimals - ✅ Use meaningful variable names in expressions
- ✅ Understand operator precedence or use parentheses
- ✅ Avoid side effects in expressions (like
++in complex expressions)
Common Mistakes
- ❌ Forgetting that integer division truncates:
5 / 2 = 2(not 2.5) - ❌ Using
=instead of==in comparisons - ❌ Confusing
&&(logical) with&(bitwise) - ❌ Not understanding operator precedence
- ❌ Modulus with floating-point numbers (only works with integers)
Next Module
In Module 4, we'll learn about Control Flow - how to make decisions with if/else statements and repeat code with loops!
Hands-on Examples
Arithmetic Operators
#include <iostream>
using namespace std;
int main() {
int a = 15, b = 4;
cout << "a = " << a << ", b = " << b << endl;
cout << "Addition: " << a + b << endl;
cout << "Subtraction: " << a - b << endl;
cout << "Multiplication: " << a * b << endl;
cout << "Division: " << a / b << endl;
cout << "Modulus: " << a % b << endl;
// Integer division note
cout << "\nNote: Integer division truncates:" << endl;
cout << "15 / 4 = " << (15 / 4) << " (not 3.75)" << endl;
// For decimal division, use double
double x = 15.0, y = 4.0;
cout << "15.0 / 4.0 = " << (x / y) << endl;
return 0;
}This example demonstrates all basic arithmetic operators. Note that integer division truncates the decimal part. To get decimal results, use floating-point types (double or float).
Sample Output
a = 15, b = 4 Addition: 19 Subtraction: 11 Multiplication: 60 Division: 3 Modulus: 3 Note: Integer division truncates: 15 / 4 = 3 (not 3.75) 15.0 / 4.0 = 3.75
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Hello World
BeginnerWrite your first C++ program and see why each of its four lines matters: #include, using namespace std, main, cout, and return 0. Made for day-one students.
Display Your Name
BeginnerStore your name in a C++ string variable and print it with cout and endl. Covers #include <string>, chaining <<, and how a string differs from a char array.
User Input
BeginnerRead a name and an age from the keyboard with cin in C++. See why cin >> stops at the first space, when to use getline, and how a bad number breaks the stream.