发布于: 2024-1-29最后更新: 2024-2-4字数 00 分钟

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
  1. Update the value
  1. Return the new (updated) value
Postfix Increment/Decrement i++ , i--
  1. Save the old value (temporary)
  1. Update the value
  1. 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 value
The 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:
 

机器学习1 - 概述
机器学习1 - 概述
公告
type
status
date
slug
summary
tags
category
icon
password
🎉欢迎体验 ChatGPT Next 🎉