简体   繁体   English

在C99中的嵌套for循环中声明计数器变量的最佳实践

[英]Best practice to declaring counter variables in nested for loops in C99

I'm asking which is the best practice between this two implementation: 我问这两个实现之间的最佳实践是什么:

for ( int i = 0; i < 5; i++ )
    for ( int j = 0; j < 5; j++ )
        ...some code here...

...other code...

for ( int i = 0; i < 5; i++ )
    for ( int j = 0; j < 5; j++ )
        ...some code here...

or this one: 或这一个:

beginning of function/main
int i,j;

...some code...

for ( i = 0; i < 5; i++ )
    for ( j = 0; j < 5; j++ )
        ...some code here...

...other code...

for ( i = 0; i < 5; i++ )
    for ( j = 0; j < 5; j++ )
        ...some code here...

In other words is it better: 换句话说更好:

  1. declaring counter loops one time for all and defining them inside each loop 一次声明所有计数器循环,并在每个循环中定义它们
  2. or declaring them every time? 还是每次都声明?

Thank you 谢谢

EDIT: My question is: Is it better to perform N declarations (and definitions) for 2 variables or 2 declarations and N definitions ? 编辑:我的问题是: 是否最好为2个变量或2个声明和N个定义执行N个声明(和定义)?

EDIT2: Ok now I understand. EDIT2:好的,现在我明白了。 I didn't know that declaration only affect the compilation and not the execution ( I saw assembly language of C99 compiled source file). 我不知道声明只会影响编译,而不会影响执行(我看到了C99编译源文件的汇编语言)。 So there's no difference and Lundin's answer shows the standard to use. 因此没有区别,Lundin的答案显示了要使用的标准。

This is actually not opinion-based, but there exists a widely recognized industry standard: 这实际上不是基于意见的,但是存在公认的行业标准:

Reduce the scope of a local variable as much as possible. 尽可能减小局部变量的范围。

This is the very reason why C++ and C99 allow iterator declarations inside the loop itself. 这就是C ++和C99允许在循环本身内部进行迭代器声明的原因。 Meaning that the first version is better, period. 意思是说,第一个版本比较好。

However , the second version has to be used if you need to know the iterator values after the loop has finished, or if you need C90 backwards-compatibility. 但是 ,如果您需要在循环完成后知道迭代器值,或者需要C90向后兼容,则必须使用第二个版本。

Always keep the scope of variables as tight as possible. 始终保持变量的范围尽可能紧凑。

Your second option leaks i and j unnecessarily into the surrounding scope, so is not to be preferred. 您的第二种选择会不必要地将ij泄漏到周围的示波器中,因此不被首选。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM