gpt4 book ai didi

GOPL : Binary assignment operator "saves us from re-evaluation?"

转载 作者:IT王子 更新时间:2023-10-29 01:14:44 25 4
gpt4 key购买 nike

Go 编程语言 (GOPL) 的第 36 页包含以下内容:

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.

我不明白关于重新评估的部分。作者的意思是这样吗

count[x] = count[x] * scale

count[x] *= scale

编译成不同的字节码?

最佳答案

这两个版本可能功能不同(感谢您的提示,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)
}

(你可以玩一下 here 。)

等效的 C 程序以完全相同的方式运行。

这让我感到惊讶的事实本身就令人惊讶:我很少调用函数来直接获取数组索引,所以我从来没有想过这个想法。

关于GOPL : Binary assignment operator "saves us from re-evaluation?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com