• Advertisement

Archived

This topic is now archived and is closed to further replies.

local variable vs loop local variable

This topic is 5408 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

well my question is simple : what is better ?? ----------- long i; for (i = 0 ; i < COUNT ; ++i) { } ----------- or ----------- for (long i = 0 ; i < COUNT ; ++i) { }

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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){...}

vs

for(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

Share this post


Link to post
Share on other sites
ok, it seems that my question was stoopid
sorry for that....
anyway thanks for anwsering !!

Share this post


Link to post
Share on other sites

  • Advertisement