Best practice to declaring counter variables in nested for loops in C99

試著忘記壹切 提交于 2019-12-08 12:24:57

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/46543170/best-practice-to-declaring-counter-variables-in-nested-for-loops-in-c99

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!