C++ operators
Created By: chatGPT
In C++, operators are special symbols that perform operations on variables and values. They can be categorized into several types based on the operation they perform, such as arithmetic, relational, logical, and more.Arithmetic operators are used to perform basic mathematical operations. Common arithmetic operators include:
Addition (+), Subtraction (-), Multiplication (*), Division (/), and Modulus (%)
Relational operators are used to compare two values. They return a boolean result: true or false.int a = 10;
int b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int prod = a * b; // 30
int quot = a / b; // 3
int mod = a % b; // 1
Equal to (==), Not equal to (!=), Greater than (>), Less than (<), Greater than or equal to (>=), and Less than or equal to (<=)
Logical operators are used to combine multiple boolean expressions. The most common logical operators are:bool isEqual = (a == b); // false
bool isNotEqual = (a != b); // true
bool isGreater = (a > b); // true
bool isLesser = (a < b); // false
Logical AND (&&), Logical OR (||), and Logical NOT (!)
Bitwise operators perform operations on binary representations of integers.bool x = true;
bool y = false;
bool result1 = x && y; // false
bool result2 = x || y; // true
bool result3 = !x; // false
Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^), Bitwise NOT (~), Left shift (<<), and Right shift (>>)
Assignment operators are used to assign values to variables. The most common assignment operator is '='. There are also combined operators for shorthand operations:int bit1 = 5; // 0101 in binary
int bit2 = 3; // 0011 in binary
int andResult = bit1 & bit2; // 1 (0001)
int orResult = bit1 | bit2; // 7 (0111)
int xorResult = bit1 ^ bit2; // 6 (0110)
+=, -=, *=, /=, and %=
Ternary operator is a shorthand way of performing conditional assignments. It takes three operands and is often used for simple if-else conditions.int value = 10;
value += 5; // value is now 15
value -= 2; // value is now 13
value *= 2; // value is now 26
value /= 2; // value is now 13
value %= 5; // value is now 3
The syntax is:
Understanding these operators is crucial for writing effective C++ programs, as they enable developers to manipulate data and control the flow of execution efficiently.condition ? valueIfTrue : valueIfFalse
int age = 18;
string canVote = (age >= 18) ? "Yes" : "No"; // canVote is "Yes"