02 April 2023

C++ 核心指南目录

“Declare an object const or constexpr unless you want to modify its value later on”

理由

这样你不会一不留神改值。还可能给编译器提供优化的机会。

例子

void f(int n)
{
    const int bufmax = 2 * n + 2;  // good: we can't change bufmax by accident
    int xmax = n;                  // suspicious: is xmax intended to change?
    // ...
}

强化

检查变量是否实际改动,不然打上标记。