在单个函数中回收变量名
我有一个包含两个 for
循环的函数,并且我使用一个名为 count
的变量作为计数器。我选择回收该名称,因为第一个循环将在第二个循环开始之前完全完成其执行,因此计数器不会相互干扰。 G++ 编译器通过以下警告对此表示反对:
error: name lookup of ‘count’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)
变量回收是否被认为是专业软件开发中的不良实践,或者是否是一个情境问题,以及我在这里错过了哪些其他含义?
I have a function that contains two for
loops, and I'm using a variable called count
as the counter. I've chosen to recycle the name as the the first loop will finish it's execution completely before the second one begins, so there is no chance of the counters interfering with each other. The G++ compiler has taken exception to this via the following warning:
error: name lookup of ‘count’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)
Is variable recycling considered bad practice in professional software development, or is it a situational concern, and what other implications have I missed here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你在做这个吗?
我怀疑 gcc 会喜欢这样,因为第二个 count 不在范围内。我认为它仅适用于第一个
for
循环,但gcc
有接受不良代码的选项。如果您使第二个 int 计数或将第一个移至外部范围,gcc 应该会很高兴。这取决于具体情况,但我一般不会重用变量。变量的名称应该反映其用途,并且通过函数进行部分切换可能会造成混乱。声明您需要什么,让编译器负责优化。
Are you doing this?
I doubt
gcc
would like that, as the secondcount
isn't in scope. I think it only applies to the firstfor
loop, butgcc
has options to accept poor code. If you either make the secondint count
or move the first to the outer scope,gcc
should be happy.This depends on the circumstances, but I generally don't reuse variables. The name of the variable should reflect its purpose, and switching part way through a function can be confusing. Declare what you need, let the compiler take care of the optimizations.
Steve McConnell 建议不要在 Code Complete 的函数中重用局部变量。
他并不是专业软件开发实践中的权威声音,但他已经是您最接近的权威声音了。
争论的焦点是这使得阅读代码变得更加困难。
你在数什么?之后命名变量。
Steve McConnell recommends not reusing local variables in functions in Code Complete.
He's not the definitive voice of practice in professional software development, but he's about as close as you're going to get to a definitive voice.
The argument is that it makes it harder to read the code.
What are you counting? Name the variables after that.
听起来您正在 for 中定义变量?即“for (int count=0; count++; count < x)”?如果是这样,那就可能有问题,而且不清楚。如果您要在第二个 for 循环中使用它,请在两个循环外部定义它。
It sounds like you're defining the variable in the for? i.e. "for (int count=0; count++; count < x)"? If so, that could be problematic, as well as unclear. If you're going to use it in a second for loop define it outside both loops.
如果您使用像这样的循环计数器变量,那么它通常并不重要。
但是,如果您打算隐藏另一个变量:
这是一个危险信号。
If you're using a loop counter variables like this, then it usually doesn't matter.
however, if you're intending to shadow another variable:
that's a red flag.