前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​NR.1:不要坚持所有声明都应该放在函数顶部

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

作者头像
面向对象思考
发布2020-11-10 11:16:34
3940
发布2020-11-10 11:16:34
举报

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(反面示例)

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-11-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • NR.1: Don't insist that all declarations should be at the top of a function
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档