An operator is a symbol that causes the compiler to take an action such as specific mathematical or logical manipulation. There are four main classes of operators arithmetic, relational, logical, and bitwise. In addition, there are some special operators for particular tasks.
Below are the types of operators to perform different types of operations in C++ language.
If more than one operator is involved in an expression, C++ language has a predefined rule of priority for the operators. This rule of priority of operators is called operator precedence. The precedence of operator species that which operator will be evaluated first and next. The associativity specifies the operator direction to be evaluated, it may be left to right or right to left.
The precedence of arithmetic operators (*, %, /, +, -) is higher than the relational operators (==, != , >, <, >= ,<= ) and precedence of relational operators is higher than the logical operators ( && , || , ! ).
Let's understand the precedence by the example given below:
int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before + (additive operator).
The precedence and associativity of C++ operators is given below:
Category | Operator | Associativity |
---|---|---|
Postfix (Highest) | () [] -> . ++ - - |
Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof |
Right to left |
Multiplicative | * / % |
Left to right |
Additive | + - |
Right to left |
Shift | << >> |
Left to right |
Relational | < <= > >= |
Left to right |
Equality | == != |
Right to left |
Bitwise AND | & |
Left to right |
Bitwise XOR | ^ |
Left to right |
Bitwise OR | | |
Right to left |
Logical AND | && |
Left to right |
Logical OR | || |
Left to right |
Conditional | ?: |
Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= |
Right to left |
Comma (Lowest) | , |
Left to right |