avatar

🧊foril

avatar

🧊foril

Python 与 C++ 运算符优先级常见错误

2023-11-06 -

在 Python 和 C++ 中,运算符优先级是不同的,有一些常用的语句返回的结果由于优先级的不同会有区别,可能会造成一些使用时的错误,比如:

# python 1 & 3 == 1 # True
// c++ bool result = 1 & 3 == 1; cout << result << endl; // 0

在 Python 中,& 的优先级比 == 高,所以先计算 1 & 3,结果为 1,然后再计算 1 == 1,结果为 True
而在 C++ 中,== 的优先级比 & 高,所以先计算 3 == 1,结果为 False,然后再计算 1 & False,结果为 0
在编译这段代码时, clang++ 也会给出警告:

test.cpp:6:21: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses] bool result = 1 & 3 == 1; ^~~~~~~~ test.cpp:6:21: note: place parentheses around the '==' expression to silence this warning bool result = 1 & 3 == 1; ^ ( ) test.cpp:6:21: note: place parentheses around the & expression to evaluate it first bool result = 1 & 3 == 1; ^ ( ) 1 warning generated.

接下来附上 Python 和 C++ 的运算符优先级表格,方便以后查阅。

Python 运算符优先级

以下表格总结了Python中的运算符优先级,从最高优先级(最具约束力)到最低优先级(最少约束力)。同一框中的运算符具有相同的优先级。除非明确给出语法,否则运算符都是二元的。同一框中的运算符从左到右分组(除了指数和条件表达式,它们从右到左分组)。

请注意,comparisons、membership tests 以及 identity tests 都具有相同的优先级,并具有从左到右的链接特性。

OperatorDescription
(expressions...), [expressions...], {key: value...}, {expressions...}Binding or parenthesized expression, list display, dictionary display, set display
x[index], x[index:index], x(arguments...), x.attributeSubscription, slicing, call, attribute reference
await xAwait expression
**Exponentiation[^5]
+x, -x, ~xPositive, negative, bitwise NOT
*, @, /, //, %Multiplication, matrix multiplication, division, floor division, remainder[^6]
+, -Addition and subtraction
<<, >>Shifts
&Bitwise AND
^Bitwise XOR
``
in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership tests and identity tests
not xBoolean NOT
andBoolean AND
orBoolean OR
ifelseConditional expression
lambdaLambda expression
:=Assignment expression

C++ 运算符优先级

PrecedenceOperatorDescriptionAssociativity
1::Scope resolutionLeft-to-right →
2a++ a--Suffix/postfix increment and decrementLeft-to-right →
2<type>() <type>{}Functional cast
2a()Function call
2a[]Subscript
2. ->Member access
3++a --aPrefix increment and decrementRight-to-left ←
3+a -aUnary plus and minus
3! ~Logical NOT and bitwise NOT
3(<type>)C-style cast
3*aIndirection (dereference)
3&aAddress-of
3sizeofSize-of [^1]
3co_awaitawait-expression (C++20)
3new new[]Dynamic memory allocation
3delete 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 and > and respectively
10== !=For equality operators = and respectively
11a&bBitwise AND
12^Bitwise XOR (exclusive or)
13``Bitwise OR (inclusive or)
14&&Logical AND
15``
16a?b:cTernary conditional [^2]Right-to-left ←
16throwthrow operator
16co_yieldyield-expression (C++20)
16=Direct assignment (provided by default for C++ classes)
16+= -=Compound assignment by sum and difference
16*= /= %=Compound assignment by product, quotient, and remainder
16<<= >>=Compound assignment by bitwise left shift and right shift
16&= ^= `=`Compound assignment by bitwise AND, XOR, and OR
17,CommaLeft-to-right →

参考