我正在阅读another SO question关于for
循环内变量声明的答案。接受的答案带来了这个非常有用的代码示例,我通过在外部添加额外的for循环来稍微扩展:
for (int j=0; j<N; j++)
{
int i, retainValue;
for (i=0; i<N; i++)
{
int tmpValue;
/* tmpValue is uninitialized */
/* retainValue still has its previous value from previous loop */
/* Do some stuff here */
}
/* Here, retainValue is still valid; tmpValue no longer */
}
如同thigs一样,tmpValue
只能在内部for
内部使用,并且它的存在将在内环的生命结束时停止。但是,因为循环是在另一个循环中级联的,并且假设我实际上希望tmpValue
在整个外部循环执行期间保留其值,所以将static
关键字分配给{是一种好的做法{1}}?
tmpValue
我问的原因是,在内循环中定义for (int j=0; j<N; j++)
{
int i, retainValue;
for (i=0; i<N; i++)
{
static int tmpValue;
/* tmpValue is uninitialized */
/* retainValue still has its previous value from previous loop */
/* Do some stuff here */
}
/* Here, retainValue is still valid; tmpValue no longer */
}
的某些论据与代码的可读性和最优性有关。我不确定我的第二个例子是否仍然如此。
答案 0 :(得分:1)
for (int j=0; j<N; j++)
{
int i, retainValue;
for (i=0; i<N; i++)
{
static int tmpValue;
// tmpValue is uninitialized only on first run of this piece of code.
// If you run this "for" procedure again tmpValue will be already
// initialized and will have last value
}// tmpValue is not destroyed here, but becomes inaccessible
}
因此,如果您需要在for循环之外使用tmpValue。只是在外面宣布。
int tmpValue;
for (int j=0; j<N; j++)
....
答案 1 :(得分:0)
你所做的就是完全打破通过添加静态(和线程)来调用多功能函数的能力,但为了简单起见,现在让我们继续使用单线程的想法。让我举例说明。
doLoop(a);
doLoop(b);
看起来它正在用a和b做一些事情;但如果我想再次从头开始,doLoop(c)
我不能。但是,如果我返回我正在使用的值;并给它一个默认值0,然后突然我可以做
auto x = doLoop(a);
x = doLoop(a, x);
auto y = doLoop(c);
这将函数中的LOGIC与DATA完全分开;从长远来看,这几乎总能使生活更轻松。
答案 2 :(得分:-2)
静态变量确实具有程序的生命周期,但它们仍遵循范围规则。