在C++中,最小化变量的作用域

huangapple go评论76阅读模式
英文:

Minimalizing variable's scope in C++

问题

我已经在编程一段时间了,开始尝试改进我的代码。因为我真的讨厌创建大量仅在长函数中使用一次的变量,所以通过使用大括号来缩短变量范围是一个好的做法吗?
例如:
而不是写:

void fcn()
{
  int var1;
  // 函数的某个部分
  // 使用var1;
  // 函数的其余部分
}

写成:

void fcn()
{
  // 函数的某个部分
  {
    int var1;
    // 使用var1;
  }
  // 函数的其余部分
}
英文:

I am programming for a while now and I've started trying to improve my code. Since I really hate creating bazillion of variables that are used only once in long function, is it good practice to shorten variable scope by using brackets?
i.e.
instead writing:

void fcn()
{
  int var1;
  // some part of fcn
  // use of var1;
  // rest of fcn
}

write:

void fcn()
{
  // some part of fcn
  {
    int var1;
    // use of var100;
  }
  // rest of fcn
}

答案1

得分: 9

是的,将变量的范围尽量保持紧凑确实是一个好主意。

在您的情况下,除非您绝对确定您的代码使用var1将只在fcn中使用(根据我的经验,我倾向于误判断这一点),否则您可以将该代码拆分到一个单独的函数中。这样您的程序将更好地扩展,并且测试也会更简单。否则,继续像您目前所做的那样使用作用域块。

英文:

Yes it is indeed a good idea to keep the scope of variables as tight as possible.

In your case, unless you are absolutely certain that your code using var1 will only ever be used in fcn (and if my experience is anything to go by, I tend to misjudge that), you could split that code out to a separate function. Your program will scale better that way, and testing will also be simpler. Else, use scope blocks as you currently do.

答案2

得分: 6

这种方法在某些情况下确实是一种良好的实践。

它在“if/range for/while/case”语句中如此广泛使用,以至于在C++17和C++20中添加了这些语句中的显式初始化器。

英文:

There are certainly context in which this approach is a good practice.

It is so wide spreaded around 'if/range for/while/case' statements that explicit initializer in those statement were added in C++17 and C++20.

答案3

得分: 0

你不应该在任何地方int var1;

首先,var1 是一个糟糕的名称。

其次,如果任何代码路径在赋值之前读取 var1,那么现在可能会出现未定义的行为。

建议使用:

int meaningfulName = initialValue;

或者更好的是:

const int meaningfulName = value;

做到这一点后,你所选择的作用域将更受限制。如果仍然有选择的余地,优先选择最窄的作用域。

英文:

You shouldn't write int var1; anywhere.

Firstly var1 is a terrible name.

Secondly you now have the potential for undefined behaviour, if any code path can read var1 before it is assigned.

Prefer

int meaningfulName = initialValue;

Or even better

const int meaningfulName = value;

Having done that, the scopes you are choosing between are more restricted. If there is still a choice, prefer the narrowest scope possible.

huangapple
  • 本文由 发表于 2020年1月3日 20:13:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定