• Advertisement
Sign in to follow this  

Simple Loop Question

This topic is 4872 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

Here is a simple loop
for (int i = 0; i < GetSomeNumber(); i++) { }
Question: is GetSomeNumber() called every trip through the loop or is it called once and compared against on every iteration? If it gets called every time, i could certainly optimize a lot of code with a simple caching beforehand:
int limit = GetSomeNumber();
for (int i = 0; i < limit; i++) { }

Share this post


Link to post
Share on other sites
Advertisement
It depends on the details. If the compiler can determine that the function will always return the same number inside the loop, then it will be optimized away. Different compilers can make such determinations with different levels of success. When in doubt, turn on the 'generate assembly output' option for your compiler and check to see if it calls the function each iteration.

Share this post


Link to post
Share on other sites
Quote:
Original post by snk_kid

for(int foo = 0, bar = foobar_size(); foo < bar; foo++) { /* YADA - YADA */ }


ooooo...

please accept my humble thanks for teaching me your great wisdom ;-)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement