问题描述
为什么会出现以下表达式:
total += *start++;
评估:
total += (*start)++;
而不是:
total += *(start++); // though this doesn't really matter either it would be the same
++
(后缀增量)和 *
(解引用具有相同的优先级并从右到左关联,那么为什么不首先评估 ++
后缀?
或者,后缀是否在序列点之后求值,等等:
total += *++start
将评估为:
total += *(++start)
但是因为后缀发生在:
total += *start++
将评估为:
total += (*start)++;
换句话说,从右到左结合性在上面的表达式中并不重要,因为在表达式求值过程中,即使是 post-fix 也是在 not 之后求值的?
解决方法
后缀 ++
运算符 确实 比取消引用运算符 *
具有更高的优先级。所以表达式解析为:
total += *(start++);
您可能会感到困惑的是,后缀 ++
运算符的结果是操作数 before 递增。实际增量是表达式的无序副作用。
因此该表达式采用 start
的原始值,取消引用它,并将该值添加到 total
。到表达式完全求值时,start
递增。
请注意,这不同于:
total += (*start)++;
因为这会增加 start
指向的内容而不是 start
本身。