Introduction to C++ | Operators
C++ Operators
In C++, operators are symbols that perform operations on variables and values. C++ supports a wide range of operators, categorized based on their functionality.
Categories of Operators
C++ operators can be broadly classified into several categories:
1. Arithmetic Operators
- +: Addition
- -: Subtraction
- *: Multiplication
- /: Division
- %: Modulus (remainder of division)
2. Relational (Comparison) Operators
- ==: Equal to
- !=: Not equal to
- <: Less than
- >: Greater than
- <=: Less than or equal to
- >=: Greater than or equal to
3. Logical Operators
- &&: Logical AND
- ||: Logical OR
- !: Logical NOT
4. Assignment Operators
- =: Assigns value to a variable
- +=: Adds and assigns
- -=: Subtracts and assigns
- *=: Multiplies and assigns
- /=: Divides and assigns
5. Increment and Decrement Operators
- ++: Increment operator (adds 1 to a variable)
- --: Decrement operator (subtracts 1 from a variable)
6. Bitwise Operators
- &: Bitwise AND
- |: Bitwise OR
- ^: Bitwise XOR
- ~: Bitwise NOT
- <<: Left shift
- >>: Right shift
7. Ternary (Conditional) Operator
- ?:: Conditional operator, shorthand for `if-else`
8. Miscellaneous Operators
- &: Address-of operator
- *: Pointer dereference operator
- sizeof: Returns the size of a variable or data type
- ,: Comma operator (used to separate multiple expressions)
Code Example: Using C++ Operators
Here's an example of using different types of operators in a C++ program.
Code Example
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
// Arithmetic Operators
int sum = a + b;
int diff = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
// Relational Operator
bool isEqual = (a == b);
// Logical Operators
bool isTrue = (a > b) && (b > 0);
// Increment Operator
a++;
// Output the results
cout << "Sum: " << sum << endl;
cout << "Difference: " << diff << endl;
cout << "Product: " << product << endl;
cout << "Quotient: " << quotient << endl;
cout << "Remainder: " << remainder << endl;
cout << "Are a and b equal? " << isEqual << endl;
cout << "Logical Check (a > b && b > 0): " << isTrue << endl;
cout << "Incremented value of a: " << a << endl;
return 0;
}
Output
Sum: 15
Difference: 5
Product: 50
Quotient: 2
Remainder: 0
Are a and b equal? 0
Logical Check (a > b && b > 0): 1
Incremented value of a: 11
Difference: 5
Product: 50
Quotient: 2
Remainder: 0
Are a and b equal? 0
Logical Check (a > b && b > 0): 1
Incremented value of a: 11
Pro Tip:
💡 Pro Tip
Operators are essential for performing various calculations and comparisons in C++. Be sure to understand the different categories and use them appropriately for efficient coding. Pay attention to operator precedence to ensure your expressions are evaluated as intended.