在C99中嵌套for循环中声明计数器变量的最佳做法 [英] Best practice to declaring counter variables in nested for loops in C99

查看:163
本文介绍了在C99中嵌套for循环中声明计数器变量的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(int i = 0; i< ; 5; i ++)
for(int j = 0; j <5; j ++)
...这里的一些代码...

...其他代码。 (int j = 0; j <5; j ++)
...一些(int i = 0; i <5; i ++)
...

这里的代码...

或这个:

 函数开头/ main 
int i,j;

...某些代码...

(i = 0; i <5; i ++)
(j = 0; j < 5; j ++)
...这里的一些代码...

...其他代码...

for(i = 0; i< 5; i ++)
for(j = 0; j <5; j ++)
...这里的一些代码...


  1. 在每个循环中定义它们

  2. 或每次声明它们

谢谢

>

编辑:
我的问题是:
对2个变量或2个声明执行N个声明(和定义) N的定义?



编辑2:
现在我明白了。我不知道这个声明只影响编译而不影响执行(我看到了C99编译源文件的汇编语言)。所以没有什么区别,Lundin的答案显示了使用标准。

解决方案

这实际上不是基于意见的,但是存在广泛认可的行业标准:

尽可能减少局部变量的范围。

这就是为什么C ++和C99在循环内部允许迭代器声明的原因。这意味着第一个版本更好,期限。



然而,如果您需要知道迭代器值之后,必须使用第二个版本循环已经完成,或者如果你需要C90的向后兼容。


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 ?

EDIT2: Ok now I understand. I didn't know that declaration only affect the compilation and not the execution ( I saw assembly language of C99 compiled source file). So there's no difference and Lundin's answer shows the standard to use.

解决方案

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. 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.

这篇关于在C99中嵌套for循环中声明计数器变量的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆