【问题标题】:Associativity of the same operator precedence -- *start++相同运算符优先级的结合性 -- *start++
【发布时间】:2021-02-06 03:48:29
【问题描述】:

为什么是下面的表达式:

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)++;

换句话说,Right-to-Left 关联性在上述表达式中并不重要,因为即使在表达式求值期间,也不会计算后缀?

【问题讨论】:

    标签: c operator-precedence


    【解决方案1】:

    后缀++ 运算符确实 比取消引用运算符* 具有更高的优先级。所以表达式解析为:

    total += *(start++);
    

    您可能会感到困惑的是,后缀++ 运算符的结果是操作数之前它被递增。实际的增量是表达式的未排序副作用。

    所以这个表达式获取start 的原始值,取消对它的引用,然后将该值添加到total。当表达式被完全计算时,start 会递增。

    请注意,这不同于:

    total += (*start)++;
    

    因为这会增加 start 指向的内容,而不是 start 本身。

    【讨论】:

    猜你喜欢
    • 2021-05-05
    • 2011-07-07
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多