首页 文章详情

C++核心准则​NR.1:不要坚持所有声明都应该放在函数顶部

面向对象思考 | 370 2020-11-03 07:02 0 0 0
UniSMS (合一短信)

NR.1: Don't insist that all declarations should be at the top of a function

NR.1:不要坚持所有声明都应该放在函数顶部


Reason(原因)

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


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter