NR.1:不要坚持所有声明都应该放在函数顶部
The "all declarations on top" rule is a legacy of old programming languages that didn't allow initialization of variables and constants after a statement. This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
“将所有所有声明放在最上面”规则是旧编程语言的遗产,该编程语言(就是C语言,译者注)不允许在语句后初始化变量和常量。 这将导致更长的程序,更多由于变量未初始化或错误初始化引发的错误。
Example, bad(反面示例)
int use(int x)
{
int i;
char c;
double d;
// ... some stuff ...
if (x < i) {
// ...
i = f(x, d);
}
if (i < x) {
// ...
i = g(x, c);
}
return i;
}
The larger the distance between the uninitialized variable and its use, the larger the chance of a bug. Fortunately, compilers catch many "used before set" errors. Unfortunately, compilers cannot catch all such errors and unfortunately, the bugs aren't always as simple to spot as in this small example.
未初始化变量与使用该变量的代码之间的距离越大,发生错误的机会越大。幸运的是,编译器可以捕获许多“设置前使用”错误。不幸的是,编译器无法捕获所有此类错误,这些错误并不总是像这个小例子中那样容易发现。
Alternative(替代方案)
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nr1-dont-insist-that-all-declarations-should-be-at-the-top-of-a-function