且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于for(),为什么使用i ++而不是++ i?

更新时间:2022-11-01 17:27:42

我的理论(为什么i ++更时尚)是当人们学习C(或C ++)时,他们最终会学习如下代码迭代:

My theory (why i++ is more fashionable) is that when people learn C (or C++) they eventually learn to code iterations like this:

while( *p++ ) {
    ...
}

请注意,修复后的表格在这里很重要(使用中缀表单将创建一个一次性类型的错误。)

Note that the post-fix form is important here (using the infix form would create a one-off type of bug).

什么时候写循环 ++ i i ++ 并不重要,使用后缀形式可能会更自然。

When the time comes to write a for loop where ++i or i++ doesn't really matter, it may feel more natural to use the postfix form.

ADDED:我上面写的内容确实适用于原始类型。在使用原始类型编写代码时,您倾向于快速地执行操作并自然地执行操作。这是我需要附加到我的理论上的重要警告。

ADDED: What I wrote above applies to primitive types, really. When coding something with primitive types, you tend to do things quickly and do what comes naturally. That's the important caveat that I need to attach to my theory.

如果 ++ 是一个重载的运算符C ++类(Rich K.在评论中建议的可能性)当然你需要非常谨慎地编写涉及这些类的循环,而不是做一些自然而然的简单事情。

If ++ is an overloaded operator on a C++ class (the possibility Rich K. suggested in the comments) then of course you need to code loops involving such classes with extreme care as opposed to doing simple things that come naturally.