dongqiu3709 2017-10-26 02:12
浏览 58
已采纳

GOPL:二进制赋值运算符“可以避免重新评估?”

Page 36 of the Go Programming Language (GOPL) contains the following:

Each of the arithmetic and bitwise binary operators has a corresponding assignment operator allowing, for example, the last statement to be rewritten as

count[x] *= scale

which saves us from having to repeat (and re-evaluate) the expression for the variable.

I do not understand the part about re-evaluation. Do the authors mean to say that

count[x] = count[x] * scale

and

count[x] *= scale

compile to different bytecode?

  • 写回答

1条回答 默认 最新

  • dongmi4927 2017-10-26 11:03
    关注

    The two versions may be functionally different (thank you for the hint, Volker):

    package main
    
    import "fmt"
    
    var idx int
    func n() int {
        idx++
        return idx - 1
    }
    
    func main() {
        var nums = [2](int){ 1, 2 }
        var adj = 10
    
        if true {
            nums[ n() ] += adj                   // Prints [11 2]
        } else {
            nums[ n() ] = nums[ n() ] + adj      // Prints [12 2]
        }
    
        fmt.Println("%v", nums)
    }
    

    (You can play with it here.)

    An equivalent C program behaves in exactly the same way.

    The fact that this was surprising to me is itself surprising: I seldom call functions to get an array index directly, so the thought never crossed my mind.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图