对于循环变体比较

For loop variants comparison

本文关键字:比较 循环 于循环      更新时间:2023-10-16

有一个for循环,如下所示:

uint32_t WORD_COUNT = // ... a constant number
using Word = uint64_t;
Word mWords[WORD_COUNT];
uint32_t n = WORD_COUNT;
for (Word* w = mWords; n--; ++w) *w = Word(0); // <= Original loop

原始循环可以这样写吗?

for (uint32_t i = 0; i < n; ++i) mWords[i] = Word(0); // => Is this the same loop?

用原来的形状写循环有什么好处吗?

如果循环用于初始化该数组,则只需编写

uint32_t WORD_COUNT = // ... a constant number
using Word = uint64_t;
Word mWords[WORD_COUNT] {};
//                      ^^ 
// See e.g. https://en.cppreference.com/w/cpp/language/aggregate_initialization

否则,正如约翰提到的

您也可以使用for范围循环for (auto& w : mWords) w = Word(0);std::fill_n(mWords, n, Word(0));

我看不出像第一个发布的片段那样编写循环有任何好处。