c++ - for 循环中的 const 值

标签 c++ for-loop constants

我看过这样的代码,

方法一

for(int i = 0; i < 200; ++i) {
    do_some_stuff(i);
}

方法二

const int max_limit = 200;
for(int i = 0; i < max_limit; ++i) {
    do_some_stuff(i);
}

方法 1 相比,方法 2 有什么优势吗?

最佳答案

用有意义的名称替换整数常量通常是一种很好的做法,所以我认为这是第二种常量的主要优点。但是,如果代码真的很简单,那么额外的行可能只会让它多一行来解析。

也就是说,如果您要替换这样的东西:

for(int i = 0; i < something.size(); ++i) {
    do_some_stuff(i);
}

const int something_sz = something.size();
for(int i = 0; i < something_sz; ++i) {
    do_some_stuff(i);
}

还有一个额外的好处,它让读者和编译器都明白 something.size() 不会因调用 do_some_stuff( i).

关于c++ - for 循环中的 const 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31933538/

相关文章:

c++ - C++ 中包装器类的大小写相关可变性(例如 uint8_t 数组包装器)

javascript - 如何使用 for 循环向 JS 变量添加值?

c - 接受用户输入并在整个过程中继续使用它的变量

java - 解决 Java Checkstyle 错误 : Name 'logger' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'

c++ - 将元组的 const 引用传递给仿函数

PHP 反射 : get constant's doc comment

c++ - 创建一个 TH2,其中包含给定 bin 中变量的标准差

c++ - stb镜像写入问题

c++ - 使用 std::map 时出错

python - 在迭代中丢失两个文本文件中的行