CppCoreGuidelines ES.72 如果明显有一个循环变量,for 比 while 语句更好
05 May 2023
“Prefer a for-statement to a while-statement when there is an obvious loop variable”
理由
可读性:循环的完整逻辑在最前面就明了。可以限制循环变量的范围。
例子
std::vector<int> vec{1, 2, 3, 4, 5}; for (gsl::index i = 0; i < vec.size(); i++) { std::cout << vec[i] << "\n"; }
1 2 3 4 5
坏例子
std::vector<int> vec{1, 2, 3, 4, 5}; int i = 0; while (i < vec.size()) { std::cout << vec[i] << "\n"; i++; }
1 2 3 4 5