62,621
社区成员
发帖
与我相关
我的任务
分享

15.7.1. Evaluate Left-Hand Operand First
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.
简而言之,二元运算符左面部分必须在右面之前演算。
如果是个复合型的赋值预算 +=,-=, *= .....,符号左边的部分(也就变量名那部分)会先将变量当时的值先保存下来,然后再运行右面的表达式,最后再赋值。
int h=4;
h+=(h+=1)+(h-=h*h); // 这行5个h,分别叫做h1~h5
运算的顺序是:
h1=4,结果4暂时保存x
(h2=4)+1 = 5,写入h,结果5暂时保存y
h3=5,5暂时保存
h4=5, h5=5, 5*5=25
5-25=-20,写入h,结果-20暂时保存z
读出刚才保存的y=5和z=-20, y+z = 5 + -20 = -15
读出刚才保存的x=4,4 + -15 = -11
整个表达式及最后的h=-11