local variable vs loop local variable

Started by
5 comments, last by haust 20 years, 11 months ago
well my question is simple : what is better ?? ----------- long i; for (i = 0 ; i < COUNT ; ++i) { } ----------- or ----------- for (long i = 0 ; i < COUNT ; ++i) { }
Advertisement
It depends.

If you have only 1 for loop, 2nd is best (minus one line).
If you use Visual C++ 6, with its well-known for bug, 1st is best. If you want to write less, and have many for loops, use 1st, if you only have one, use 2nd. And so on...

ToohrVyk

What are your criteria for ''better''?

Anyway...

alternatives:

1) Design your software to make use of containers that can be used in the standard library algorithms. You''ll then use for_each and the many similar functions which perform the loops for you.

2) Move the loop into a function of its own. Then the difference between the two examples you give will be unimportant.

What machine code does your compiler produce?
quote:Original post by petewood
What are your criteria for ''better''?

Indeed. But the usual C++ way of doing it is to have a "local loop variable", like you put it. Any decent compiler should eliminate the speed difference between the two. It is also in line with the thinking that a variable (or object) shouldn''t be declared before you are going to use it.

Cédric
quote:Original post by cedricl
Any decent compiler should eliminate the speed difference between the two.

Why should there be a speed difference in the first place?
In the original example, there isn''t, but what I had in mind is

int i;for(i=0;i<10;++i){...}for(i=0;i<30;++i){...}vsfor(int i=0;i<10;++i){...}for(int i=0;i<30;++i){...} 

i.e.: the reuse of the iteration variable. A very dumb compiler could push and pop i twice in the second example... It''s pointless, I know, but that''s what sprung to mind when I answered.

Cédric
ok, it seems that my question was stoopid
sorry for that....
anyway thanks for anwsering !!

This topic is closed to new replies.

Advertisement