Skip to main content
gamedev.net
🔒 Locked

local variable vs loop local variable

Started by haust May 4, 2003 at 2:31 PM 5 replies 1.1k views
Original Post
haust
haust
well my question is simple : what is better ?? ----------- long i; for (i = 0 ; i < COUNT ; ++i) { } ----------- or ----------- for (long i = 0 ; i < COUNT ; ++i) { }
ToohrVyk
ToohrVyk
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

Qw3r7yU10p!
Qw3r7yU10p!
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?
Cedric
Cedric
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
Miserable
Miserable
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?
Cedric
Cedric
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
haust
haust
ok, it seems that my question was stoopid
sorry for that....
anyway thanks for anwsering !!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.