Operators
C++ Operators
Definition: Operators are special symbols used to perform operations on variables and values. In C++, they act as the functional heart of your code, allowing you to execute mathematical calculations, compare different pieces of data, and manage logical decisions.
Why: Beginner C++ tutorials introduce operators early because they turn static data (variables) into dynamic actions. Understanding the different groups of operators—from basic addition to complex logical evaluation—is essential for building any type of functional software logic.
Main Operator Groups
C++ operators are categorized based on the type of operation they perform:
| Category | Symbols | Description |
|---|---|---|
| Arithmetic | +, -, *, /, % |
Performs common mathematical calculations like addition and division. |
| Assignment | =, +=, -=, *= |
Assigns values to variables. Compound operators (like +=) update and assign in one step. |
| Comparison | ==, !=, >, < |
Compares two values. The result is always a boolean (true or false). |
| Logical | &&, ||, ! |
Connects two or more conditions (AND, OR) or reverses a condition (NOT). |
| Inc / Dec | ++, -- |
Increases or decreases a variable's value by exactly 1. |
Example: Arithmetic in Action
This program demonstrates the most common arithmetic operations, including the Modulus operator (%), which returns the remainder of a division:
#include <iostream> using namespace std; int main() { int a = 10, b = 3; cout << "Sum: " << a + b << endl; // 13 cout << "Difference: " << a - b << endl; // 7 cout << "Product: " << a * b << endl; // 30 cout << "Quotient: " << a / b << endl; // 3 (integer division) cout << "Remainder: " << a % b << endl; // 1 return 0; }
Key Notes
- Integer Division: When you divide two integers (like
10 / 3), C++ discards the decimal part and returns a whole number (3). To get a decimal result, at least one of the numbers must be afloatordouble. - Operator Precedence: C++ follows mathematical "BODMAS" rules. Multiplication and division are performed before addition and subtraction unless parentheses
()are used to change the order. - The Modulus Rule: The
%operator only works with integer data types. It is frequently used to check if a number is even or odd (e.g.,number % 2 == 0). - Assignment vs. Comparison: A common beginner mistake is using a single equals (
=) when they mean to compare values. Remember:=assigns a value, while==checks if two values are equal.