English 中文(简体)
在单个函数中回收变量名
原标题:Recycling variable name within single function

我有一个函数,它包含两个循环的,并且我使用一个名为count的变量作为计数器。我选择了回收名称,因为第一个循环将在第二个循环开始之前完全完成它的执行,所以计数器之间不可能相互干扰。G++编译器通过以下警告对此表示异议:

error: name lookup of ‘count’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)

变量回收在专业软件开发中是否被认为是一种糟糕的做法,还是一种情境问题,以及我在这里遗漏了哪些其他含义?

最佳回答

你在这么做吗?

for(int count = 0; ...)
{
    ...
}

for(count = 0; ...)
{
    ...
}

我怀疑gcc是否会这样,因为第二个count不在范围内。我认为它只适用于循环的第一个,但gcc可以选择接受糟糕的代码。如果您将第二个int计数或将第一个移到外部范围,gcc应该会很高兴。

这取决于具体情况,但我通常不会重用变量。变量的名称应该反映其用途,在函数的中途切换可能会令人困惑。声明您需要什么,让编译器负责优化。

问题回答

Steve McConnell建议不要在Code Complete中的函数中重用局部变量。

他不是专业软件开发实践中的权威声音,但他几乎和你即将获得的权威声音一样接近。

其论点是,这会使阅读代码变得更加困难。

你在数什么?在此之后命名变量。

听起来你在for中重新定义了变量?即“for(int count=0;count++;count<;x)”?如果是这样的话,这可能是有问题的,也可能是不清楚的。如果要在第二个for循环中使用它,请在两个循环之外定义它。

如果您使用这样的循环计数器变量,那么这通常无关紧要。

for (int i ...; ... ; ...) { 
    ... 
}
for (int i ...; ... ; ...) { 
    ... 
}

但是,如果您打算隐藏另一个变量:

int i ...;
for (int i ...; ... ; ...) { 
    ... 
}

那是危险信号。





相关问题
passing form variables into a url with php

I have the following form which allows a user to select dates/rooms for a hotel reservation. <form action="booking-form.php" method="post"> <fieldset> <div class="select-date">...

Error: "Cannot modify the return value" c#

I m using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable? public Point Origin { get; set; } Origin.X = 10; // fails with CS1612 Error ...

C-style Variable initialization in PHP

Is there such a thing as local, private, static and public variables in PHP? If so, can you give samples of each and how their scope is demonstrated inside and outside the class and inside functions?

C#/.NET app doesn t recognize Environment Var Change (PATH)

In my C# app, I am programmatically installing an Oracle client if one is not present, which requires adding a dir to the PATH system environment variable. This all works fine, but it doesn t take ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

How to dynamically generate variables in Action Script 2.0

I have a for loop in action script which I m trying to use to dynamically create variable. Example for( i = 0 ; i &lt 3 ; i++) { var MyVar+i = i; } after this for loop runs, i would like to ...