C++ tutorials  /  Operators in C++
Chapter 3 · C++

Operators in C++

An operator in C++ is a special symbol or keyword that instructs the compiler to perform a specific mathematical, relational, logical, or bitwise operation on one or more operands (values or variables). Operators are the building blocks of expressions, and C++ provides one of the richest sets of operators among mainstream languages, including support for operator overloading in user-defined types.

Think of operators as the verbs of a programming language — they tell the computer what action to perform on your data. Just like '+' means 'add these two numbers' in math class, in C++ '+' can add numbers, '==' can compare two values to check if they're equal, and '&&' can check if two conditions are both true. Some operators work on two values (like 5 + 3), some work on just one (like -5), and C++ even lets you redefine what operators mean for your own custom data types.

In an e-commerce checkout system, arithmetic operators calculate the final bill: 'total = price * quantity + tax'. Relational operators check business rules, such as 'if (cartTotal >= 500)' to apply free shipping. Logical operators combine multiple conditions, like 'if (isMember && cartTotal > 1000)' to apply a loyalty discount only if both conditions hold. In game development, the modulus operator '%' is used to check if a frame counter is divisible by a number to trigger animations at regular intervals, while bitwise operators are used in graphics programming and networking code to efficiently pack multiple flags (like player status: alive, stunned, invisible) into a single integer using bitmasks.

Without operators, a language would only be able to store data, not transform or compare it — there would be no way to calculate a total price, check if a user is old enough to register, or decide which branch of code to execute. Operators let programs make decisions, perform calculations, and manipulate data at both a high level (like comparing two objects) and a very low level (like manipulating individual bits for performance-critical embedded or systems code), which is part of why C++ is trusted for both business logic and hardware-level programming.

  • Arithmetic Operators: Perform mathematical calculations: '+' (addition), '-' (subtraction), '*' (multiplication), '/' (division), and '%' (modulus, which returns the remainder of integer division and only works with integer operands).
  • Relational (Comparison) Operators: Compare two values and return a 'bool' result: '==' (equal to), '!=' (not equal to), '>' (greater than), '<' (less than), '>=' (greater than or equal to), and '<=' (less than or equal to), commonly used in conditionals and loops.
  • Logical Operators: Combine or invert boolean expressions: '&&' (logical AND, true only if both operands are true), '||' (logical OR, true if at least one operand is true), and '!' (logical NOT, inverts a boolean value), essential for building complex conditional logic.
  • Bitwise Operators: Operate directly on the individual bits of integer values: '&' (bitwise AND), '|' (bitwise OR), '^' (bitwise XOR), '~' (bitwise NOT/complement), '<<' (left shift), and '>>' (right shift), commonly used in low-level programming, encryption, and performance optimization.
  • Assignment Operators: Assign values to variables, including the basic '=' as well as compound assignment operators like '+=', '-=', '*=', '/=', and '%=' that combine an arithmetic operation with assignment in a single step (e.g., 'x += 5' is shorthand for 'x = x + 5').
  • Increment/Decrement, Conditional, and Misc Operators: Includes '++' and '--' (increment/decrement by 1, available in prefix and postfix forms), the ternary conditional operator '?:' (a compact if-else expression), 'sizeof' (returns size of a type/variable in bytes), and the comma operator ',' (evaluates multiple expressions, returning the last one).
// General operator syntax operand1 operatorSymbol operand2; // Examples int sum = a + b; bool isEqual = (a == b); bool result = (a > 0) && (b > 0); int shifted = a << 2; x += 10; int max = (a > b) ? a : b; // ternary operator
A developer building a simple grading system needs to calculate a student's average from three test scores, check whether the average qualifies for a 'Pass' or 'Fail' using comparison and logical operators, and use the ternary operator to assign the result in a single concise line.
Arithmetic and Relational Operators in a Grading System
Calculates an average score using arithmetic operators, then evaluates pass/fail status using a relational operator.
cpp
#include <iostream> using namespace std; int main() { int test1 = 85, test2 = 90, test3 = 78; double average = (test1 + test2 + test3) / 3.0; cout << "Average: " << average << endl; bool isPass = (average >= 40); cout << "Passed: " << isPass << endl; return 0; }
Average: 84.3333 Passed: 1
The arithmetic operators '+' and '/' calculate the average, and dividing by '3.0' (a double literal) forces floating-point division instead of integer truncation. The relational operator '>=' then compares the average against the passing threshold and produces a 'bool', which 'cout' displays as 1 (true).
Logical and Ternary Operators for Combined Conditions
Demonstrates combining multiple conditions with logical operators and using the ternary operator as a shorthand for if-else.
cpp
#include <iostream> using namespace std; int main() { int age = 20; bool hasID = true; bool canEnter = (age >= 18) && hasID; cout << "Can Enter Club: " << canEnter << endl; string result = (age >= 18) ? "Adult" : "Minor"; cout << "Category: " << result << endl; return 0; }
Can Enter Club: 1 Category: Adult
The '&&' logical operator ensures 'canEnter' is only true when BOTH the age condition and 'hasID' are true. The ternary operator '?:' evaluates the condition '(age >= 18)' and assigns "Adult" if true, otherwise "Minor" — functioning as a compact one-line if-else statement.
  • Confusing Assignment (=) with Equality (==): Writing 'if (x = 5)' instead of 'if (x == 5)' is a classic bug — the single '=' assigns 5 to x and the condition becomes always true (since 5 is non-zero), silently breaking the program's logic instead of throwing a compile error in many cases.
  • Integer Division Truncation: Writing 'int average = (a + b) / 2;' when a and b are integers truncates any decimal result — e.g., '(5 + 4) / 2' gives 4, not 4.5, because integer division discards the remainder. At least one operand must be cast to 'double' or 'float' to get a precise decimal result.
  • Misunderstanding Operator Precedence: Writing 'a + b * c' assumes left-to-right evaluation, but multiplication has higher precedence than addition, so 'b * c' is computed first. Beginners often get unexpected results in complex expressions by not using parentheses to make the intended order explicit, such as writing '(a + b) * c' when that's the actual intent.
  • Confusing Prefix and Postfix Increment/Decrement: '++x' (prefix) increments the value first and then returns it, while 'x++' (postfix) returns the current value first and increments afterward. Using them interchangeably inside complex expressions like 'array[i++] = i' can produce different, confusing results and subtle off-by-one bugs.
  • Using Bitwise Operators (&, |) Instead of Logical Operators (&&, ||): Beginners sometimes write 'if (a & b)' when they mean 'if (a && b)'. Bitwise AND operates on individual bits and produces a completely different numeric result than the logical AND, which can cause incorrect conditional behavior without any compiler warning in many cases.
  • Use Parentheses to Make Operator Precedence Explicit: Even when you know the precedence rules, wrapping sub-expressions in parentheses like '(a + b) * c' improves readability for other developers and eliminates any ambiguity about the intended order of evaluation, reducing the chance of subtle logic bugs.
  • Prefer Compound Assignment Operators for Clarity and Conciseness: Use 'x += 5;' instead of 'x = x + 5;' where applicable — it's more concise, clearly communicates intent (modifying the existing value), and in some cases can be marginally more efficient depending on the compiler and data type.
  • Avoid Relying on Increment/Decrement Side Effects Within Complex Expressions: Avoid writing expressions like 'x = x++ + ++x;' where a variable is modified more than once between sequence points — the result is undefined behavior in C++ and can vary across compilers, so keep increment/decrement operations as their own separate statements when logic gets complex.
  • Use Bitwise Operators Only When You Genuinely Need Bit-Level Control: Reserve bitwise operators for scenarios like flags, permission systems, or performance-critical embedded code where bit manipulation is the correct tool, and always add comments explaining the bitmask logic, since bitwise code is significantly harder for other developers to read and maintain than standard boolean logic.
What is the difference between the '==' and '=' operators in C++?
'=' is the assignment operator, used to assign a value to a variable (e.g., 'x = 5;'), while '==' is the relational equality operator, used to compare two values and return a boolean result indicating whether they are equal (e.g., 'if (x == 5)'). Accidentally using '=' inside a conditional statement is a common bug since it silently assigns a value rather than comparing, and the condition becomes true whenever the assigned value is non-zero.
Explain the difference between prefix increment (++x) and postfix increment (x++).
Prefix increment '++x' increments the variable's value first, then returns the updated value for use in the surrounding expression. Postfix increment 'x++' returns the variable's original value for use in the expression first, and only increments it afterward. This distinction matters in expressions like 'int y = x++;' (y gets the old value of x) versus 'int y = ++x;' (y gets the new, incremented value of x).
What is operator precedence and associativity, and why do they matter in C++?
Operator precedence determines the order in which different operators are evaluated in an expression with multiple operators (e.g., multiplication and division are evaluated before addition and subtraction). Associativity determines the evaluation order when operators of the same precedence appear together (most operators are left-to-right, but assignment and some unary operators are right-to-left). Misunderstanding these rules can lead to expressions evaluating in an order the programmer didn't intend, producing subtly incorrect results.
What is the difference between logical operators (&&, ||) and bitwise operators (&, |) in C++?
Logical operators ('&&', '||') work on boolean expressions and use short-circuit evaluation, meaning the second operand isn't evaluated if the result can already be determined from the first (e.g., in 'a && b', if 'a' is false, 'b' is never evaluated). Bitwise operators ('&', '|') operate on the individual binary bits of integer operands and always evaluate both operands fully, producing a numeric result rather than a strict boolean one, making them unsuitable as direct substitutes for logical operators in conditional logic.
What is the ternary (conditional) operator, and when should it be used over a full if-else statement?
The ternary operator '?:' is a shorthand conditional expression of the form 'condition ? valueIfTrue : valueIfFalse', which evaluates to one of two values based on a boolean condition. It's best used for simple, single-value assignments where using a full if-else block would be unnecessarily verbose, such as 'int max = (a > b) ? a : b;'. However, for complex logic with multiple statements or side effects, a full if-else statement is more readable and should be preferred over nested or overly complex ternary expressions.
Write a C++ program that takes two integers and prints the result of all arithmetic operators (+, -, *, /, %) applied to them.
#include <iostream> using namespace std; int main() { int a = 17, b = 5; cout << "Sum: " << (a + b) << endl; cout << "Difference: " << (a - b) << endl; cout << "Product: " << (a * b) << endl; cout << "Quotient: " << (a / b) << endl; cout << "Remainder: " << (a % b) << endl; return 0; }
Predict the output of the following code and explain why: int x = 5; cout << x++ << " " << x << " " << ++x << endl;
The output is '5 6 7'. First, 'x++' (postfix) prints the current value of x (5) and THEN increments x to 6. Next, 'x' is printed directly, showing the now-updated value of 6. Finally, '++x' (prefix) increments x to 7 first and then prints the new value 7. Note that in modern C++ (C++17 and later), the evaluation order of operands separated by '<<' is well-defined left-to-right, though relying on multiple side effects within one statement is still considered poor practice.
Write a program using the ternary operator to determine and print whether a given number is 'Even' or 'Odd'.
#include <iostream> using namespace std; int main() { int num = 17; string result = (num % 2 == 0) ? "Even" : "Odd"; cout << num << " is " << result << endl; return 0; }

Operators are the fundamental building blocks that let C++ programs perform calculations, compare values, combine conditions, and manipulate data at both a high level and the bit level. From arithmetic and relational operators used in everyday business logic to bitwise operators used in performance-critical systems programming, understanding operator precedence, associativity, and the subtle differences between similar-looking operators (like '=' vs '==', or prefix vs postfix increment) is essential for writing correct, bug-free C++ code. Mastering operators sets the foundation for writing conditional statements, loops, and complex expressions confidently.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.