Golang语言社区go学习代码世界

go语言的++/--操作

2017-09-15  本文已影响9人  CodingCode

go语言的++/--操作

C/C++程序员的窘境

C/C++程序员在面试的时候经常会被面试官问到++/--的问题而搞晕,其实面试官自己在出题的时候也未必能弄
明白,只不过恰好在面试你之前在电脑上验证了一把,所以显得他知道的很多,不要问我怎么知道的:-)

go语言的++/--

go语言对++/--的使用做了优化(限制),个人感觉这种限制非常好;C/C++里面对++/--的使用虽然很灵活,但是这种灵活容易导致混淆,引入潜在风险。

go语言里面对++/--的限制只有一条,即:

掌握这个原则就很好理解go对++/--的使用限制了。

  1. ++/--是语句,不是表达式
  var i int
  var j int
  j = i++;

这类j=i++语句不正确,因为i++是一条语句,不是表达式,而此时需要的是表达式。

  1. 前加/后加, i++ vs. ++i
    既然++/--是语句,不是一个表达式,那么i++和++i的功能是一样的,把++放在后面只是阅读的传统习惯。

下面是官方对++/--的解释

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.
上一篇 下一篇

猜你喜欢

热点阅读