开发者

Why do people use i = i + 1 instead of i++? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel t开发者_JS百科hat this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

I've seen that in a number of loops and increments. Instead of doing i++ they do i += 1. Why is this?


Personal preference and style.


Not all languages have ++ operator (python, for one)... Probably these people come from a background in one of those languages. Also some people feel that i++ is not very clear, especially since some languages treat i++ and ++i differently.


The general reason is that there are two different versions of increment that behave differently

var i = 0;
1 == ++i // true

and

var i = 0;
1 == i++; // false

++i translates to "increment i, then evaluate" while i++ translates to "evaluate i, then increment"

When you write these expressions as i = i + 1; it's clear what the intent of the programmer was and easier to find bugs in the code. It's the same reason people write "yoda clauses" like

if(6 == x){
    //. . .
}

because if you accidentally do

if(6 = x){
    //. . .
}

it's easier to catch the mistake


Prevents excess craftiness. At least that is what Crockford says.


i = i + 1 is easier to decode in English. i++ although totally correct doesn't translate well when beginners are reading the code. The programmer was possibly trying to make their code more readable by beginners, or perhaps just not trying to be overly concerned about syntax. There's no good reason to use one over the other.


Some people find i = i + 1 or i += 1 more descriptive than i++. It's just a matter of coding style and readability. In most current languages there is no performance difference at all between the different ways.

There are some readability issues with the ++ and -- operators, but that's mostly when they are used along with other operators, it's not really a problem when they are used by themselves. An expression like ++x+-++y+-z++ for example is perfectly valid, but it's hard to see what it actually does. As the operators cause readability issues in some cases, some feel that they should always be avoided.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜