2

Let's consider following loop in C++, where A is vector or other container using .size():

for(int n=0; n < A.size(); ++n)
    cout << A[n];

I think it is equivalent to the loop below (at least in this case, if it is not really absolutely equivalent, can you help me to figure out why? I cannot find a counter-example to that)

for(int n=-1; ++n < A.size(); )
    cout << A[n];

Is using first loop somehow better than second one? I see people using first loop everywhere, but never saw a second one. Why no one do this like in second example? Are there some counter-indication to not do this? In both cases, value of n is the same when we execute second line of code, also while exiting loop, we have the same value. Can anything go wrong in the second loop?

For me, second one seems even simpler.

4

2 回答 2

7

第一个更好,因为它是传统的。第二个会让未来的读者摸不着头脑,诅咒你的名字。

于 2013-06-09T09:13:39.977 回答
4
  1. 从减一开始,然后在条件中加一以得到 0 并不是一件好事。
  2. 我非常怀疑生成的代码会有所不同(除了将零加载到寄存器可能比 -1 更优化,这可能需要完整的 32 位值,其中零通常具有简短形式或可以通过“从自身减去寄存器”或“与自身进行异或寄存器”。
  3. 使代码更难阅读是没有好处的。如果编译器出于某种原因认为这种解决方案更好,那么让它与代码混在一起。您甚至可能因为使用“不寻常”的模式而遗漏了一些优化技巧。

如果要删除for循环的第三部分,我可以建议一种更典型的方法:

for(int n=0; n < A.size();)
    cout << A[n++];

(请注意,对于“标准”类型,例如int,n++++n在任何现代编译器中应该是等效的)

于 2013-06-09T09:20:20.277 回答