type
status
date
slug
summary
tags
category
icon
password
4.1 Operators Precedence
Precedence
| Operator
| Description
| Associativity
|
1 | a++ a-— | Suffix/postfix increment and decrement | Left-to-right |
2 | +a -a ++a --a ! not ∼ | Plus/minus, Prefix increment/decrement,Logical/Bitwise Not | Right-to-left |
3 | a*b a/b a%b | Multiplication, division, and remainder | Left-to-right |
4 | a+b a-b | Addition and subtraction | Left-to-right |
5 | << >> | Bitwise left shift and right shift | Left-to-right |
6 | < <= > >= | Relational operators | Left-to-right |
7 | == != | Equality operators | Left-to-right |
8 | & | Bitwise AND | Left-to-right |
9 | ˆ | Bitwise XOR | Left-to-right |
10 | | | Bitwise OR | Left-to-right |
11 | && and | Logical AND | Left-to-right |
12 | || or | Logical OR | Left-to-right |
13 | += -= *= /= %= <<= >>= &= ˆ= |= | Compound | Right-to-left |
- Unary operators have higher precedence than binary operators
- Standard math operators (+, *, etc.) have higher precedence than
comparison, bitwise, and logic operators
- Comparison operators have higher precedence than bitwise and logic operators
- Bitwise operators have higher precedence than logic operators
- Compound assignment operators +=, -=, *=, /=, %=, ˆ=, !=, &=, >>= , <<= have lower priority
- The comma operator has the lowest precedence (see next slides)
Important: sometimes parenthesis can make an expression verbose... but they can help!
4.2 Prefix/Postfix Increment/Decrement Semantic
Prefix Increment/Decrement ++i , --i
- Update the value
- Return the new (updated) value
Postfix Increment/Decrement i++ , i--
- Save the old value (temporary)
- Update the value
- Return the old (original) value
Prefix/Postfix increment/decrement semantic applies not only to built-in types but also to objects
4.3 Assignment, Compound, and Comma Operators
Assignment and compound assignment operators have right-to-left associativity and their expressions return the assigned value
The comma operator⋆ has left-to-right associativity. It evaluates the left expression, discards its result, and returns the right expression
4.4 Spaceship Operator
C++20 provides the three-way comparison operator
<=> , also called spaceship operator, which allows comparing two objects in a similar way of strcmp . The operator returns an object that can be directly compared with a positive, 0, or negative integer valueThe semantic of the spaceship operator can be extended to any object and can greatly simplify the comparison operators overloading
4.5 Safe Comparison Operators
C++20 introduces a set of functions
<utility> to safely compare integers of different types (signed, unsigned)example:
- 作者:KaiGuo
- 链接:https://blog.kaiguov5.com/article/f398c29b-2913-475c-8d20-390bf0089e4f
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。