Saturday, August 17, 2019

C++ Interview Questions 3: Precedence of Operators



Notes:

(1) && is higher than ||

(2) the bitwise operators is higher than the logic ones: like & is higher than &&

(3) for bitwise operators: & > ^ > |

(4) << and >> are higher than bitwise and logic ones;

(5) << and >> are lower than +, -;


The following table lists the precedence and associativity of C++ operators. Operators are listed top to bottom, in descending precedence.
PrecedenceOperatorDescriptionAssociativity
1::Scope resolutionLeft-to-right
2a++   a--Suffix/postfix increment and decrement
type()   type{}Functional cast
a()Function call
a[]Subscript
.   ->Member access
3++a   --aPrefix increment and decrementRight-to-left
+a   -aUnary plus and minus
!   ~Logical NOT and bitwise NOT
(type)C-style cast
*aIndirection (dereference)
&aAddress-of
sizeofSize-of[note 1]
co_awaitawait-expression (C++20)
new   new[]Dynamic memory allocation
delete   delete[]Dynamic memory deallocation
4.*   ->*Pointer-to-memberLeft-to-right
5a*b   a/b   a%bMultiplication, division, and remainder
6a+b   a-bAddition and subtraction
7<<   >>Bitwise left shift and right shift
8<=>Three-way comparison operator (since C++20)
9<   <=For relational operators < and ≤ respectively
>   >=For relational operators > and ≥ respectively
10==   !=For relational operators = and ≠ respectively
11&Bitwise AND
12^Bitwise XOR (exclusive or)
13|Bitwise OR (inclusive or)
14&&Logical AND
15||Logical OR
16a?b:cTernary conditional[note 2]Right-to-left
throwthrow operator
co_yieldyield-expression (C++20)
=Direct assignment (provided by default for C++ classes)
+=   -=Compound assignment by sum and difference
*=   /=   %=Compound assignment by product, quotient, and remainder
<<=   >>=Compound assignment by bitwise left shift and right shift
&=   ^=   |=Compound assignment by bitwise AND, XOR, and OR
17,CommaLeft-to-right


No comments:

Post a Comment