Best practice to declaring counter variables in ne

2019-06-14 12:38发布

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.

2条回答
我只想做你的唯一
2楼-- · 2019-06-14 13:15

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.

查看更多
迷人小祖宗
3楼-- · 2019-06-14 13:34

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.

查看更多
登录 后发表回答