C++ Operators Explained | Arithmetic, Relational, Logical, Bitwise and Ternary Operator
This complete tutorial on C++ Operators explains how operators work in C++ programs. It covers arithmetic, relational, logical, bitwise, assignment, and conditional (ternary) operators with clear examples and best practices. This tutorial helps beginners understand expressions, conditions, and calculations, which are essential for writing efficient and readable C++ code.
Operators – Complete Tutorial
1. What are Operators?
Operators are symbols that perform operations on variables and values. They are used to manipulate data, compare values, and control program flow.
Example:
2. Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
| OperatorDescriptionExample | ||
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
Example:
Best Practices:
- Avoid division by zero
- Use
%only with integers
3. Relational Operators
Relational operators compare two values and return a boolean result (true or false).
| OperatorDescription | |
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Example:
4. Logical Operators
Logical operators are used to combine multiple conditions.
| OperatorDescription | |
&& | Logical AND |
| ` | |
! | Logical NOT |
Example:
Best Practices:
- Use parentheses for clarity
- Avoid complex logical expressions
5. Bitwise Operators
Bitwise operators work on individual bits of integers.
| OperatorDescription | |
& | Bitwise AND |
| ` | ` |
^ | Bitwise XOR |
~ | Bitwise NOT |
<< | Left shift |
>> | Right shift |
Example:
Use Cases:
- Low-level programming
- Performance optimization
- Embedded systems
6. Assignment Operators
Assignment operators assign values to variables.
| OperatorExampleEquivalent | ||
= | a = b | a = b |
+= | a += b | a = a + b |
-= | a -= b | a = a - b |
*= | a *= b | a = a * b |
/= | a /= b | a = a / b |
Example:
7. Conditional (Ternary) Operator
The conditional operator is a shorthand for if-else.
Syntax:
Example:
Best Practices:
- Use for simple conditions only
- Avoid nested ternary operators
Operator Precedence (Basic Idea)
Operator precedence determines the order of evaluation.
Example:
Best Practice:
- Use parentheses to improve readability
Common Mistakes to Avoid
- Confusing
=with== - Using bitwise operators instead of logical operators
- Ignoring operator precedence
- Overusing ternary operator
Summary
In this chapter, you learned about C++ operators, including arithmetic, relational, logical, bitwise, assignment, and conditional operators. Operators are fundamental to writing expressions, conditions, and calculations in C++ programs.