Now, it is time to explore C++ operators. In C++, Operators work on variables and values. Most of the operations are mathematical or logical in nature. C++ is rich in built-in operators and provides the following types of operators −
- Arithmetic Operators 🡪They are used to perform arithmetic operations on 2 or more operands. Some common operands are + (addition), - (subtraction) , * (multiplication), / (divison), %(remainder) ,++ (increment), -- (decrement). For e.g
i++;
sum = a + b;
B.Relational Operators 🡪 they are used to determine the relation between variables or values. Here, we compare two values and return the result as either true (1) or false (0). Some common relational operators are as == (check equality), != (checks inequality), > (greater than), < (lesser than), >= (greater than or equal to) and <= (less than or equal to).
For e.g.
if (x>THRESHOLD)
{
…
}
- Logical Operators 🡪 used to determine the logic between variables or values. Logical operators are && (Logical AND),|| (Logical OR Operator) and ! (Logical NOT operator).
For e.g.
if (x<5 && y>10)
{
}
- Bitwise Operators 🡪 Bitwise operator does not work on numbers but on bits. It is done bit-by-bit operation. The three Bitwise operators are & (bit wise AND), | (Bitwise OR), ^(Bitwise XOR), ~ (binary 1’s complement), << (binary left shift operator) and >> (binary left shift operator).
E.Assignment Operators 🡪 This class of operators are used for assignment. For e.g = (simple assignment), += (add AND assignment), -= (subtract AND assignment), *= (multiply AND assignment) etc.
F.Misc Operators 🡪 They are a heterogeneous operator set. It includes sizeof (used to find size of a variable), ternary operator condition ? exp1: exp2 (conditional evaluation), , operator, .(dot) and -> (arrow), cast (change type of a variable temporarily) , & (pointer address) and *(pointer access)
The operator precedence and associativity are also important. Precedence dictates priority among execution of different operators while associativity gives the direction in which operator are evaluated (left to right or right to left). Both of them affects how an expression is evaluated. For example, the multiplication operator has higher precedence than the addition operator, so * will be evaluated before +.
For example :
x = 7 * 5 + 3 - 2 * 10; //x will be equal to 18