go語(yǔ)言的++/--操作
C/C++程序員的窘境
C/C++程序員在面試的時(shí)候經(jīng)常會(huì)被面試官問(wèn)到++/--的問(wèn)題而搞暈,其實(shí)面試官自己在出題的時(shí)候也未必能弄
明白,只不過(guò)恰好在面試你之前在電腦上驗(yàn)證了一把,所以顯得他知道的很多,不要問(wèn)我怎么知道的:-)
go語(yǔ)言的++/--
go語(yǔ)言對(duì)++/--的使用做了優(yōu)化(限制),個(gè)人感覺(jué)這種限制非常好;C/C++里面對(duì)++/--的使用雖然很靈活,但是這種靈活容易導(dǎo)致混淆,引入潛在風(fēng)險(xiǎn)。
go語(yǔ)言里面對(duì)++/--的限制只有一條,即:
- ++/--是語(yǔ)句,不是表達(dá)式
掌握這個(gè)原則就很好理解go對(duì)++/--的使用限制了。
- ++/--是語(yǔ)句,不是表達(dá)式
var i int
var j int
j = i++;
這類(lèi)j=i++語(yǔ)句不正確,因?yàn)閕++是一條語(yǔ)句,不是表達(dá)式,而此時(shí)需要的是表達(dá)式。
- 前加/后加, i++ vs. ++i
既然++/--是語(yǔ)句,不是一個(gè)表達(dá)式,那么i++和++i的功能是一樣的,把++放在后面只是閱讀的傳統(tǒng)習(xí)慣。
下面是官方對(duì)++/--的解釋
Why are ++ and -- statements and not expressions? And why postfix, not prefix?
Without pointer arithmetic, the convenience value of pre- and postfix increment operators drops. By removing them from the expression hierarchy altogether, expression syntax is simplified and the messy issues around order of evaluation of ++ and --(consider f(i++) and p[i] = q[++i]) are eliminated as well. The simplification is significant. As for postfix vs. prefix, either would work fine but the postfix version is more traditional; insistence on prefix arose with the STL, a library for a language whose name contains, ironically, a postfix increment.