Why are we allowed to harass an iterating variable in a for loop [closed]
Sorry about the question being so generic, but I've always wondered about this.
In a for loop, why doesn't a compiler determine the number of times it has to run based on the initializer,condition and increment and then run开发者_Python百科 the loop for the predetermined number of times?
Even the advanced for in Java and the for in python which allow us to iterate over collections would act funny if we modified the collection.
If we do want to change the iterating variable or the object we are iterating upon, we might as well use a while loop instead of a for. Are there any advantages to using a for loop in such a case?
Since no language does a for loop the way I have described, there must be a lot of things I haven't thought about. Please point out the same.
That's what an optimizing compiler can do if it decides that's the right optimization. It's called loop unrolling and you can encourage it in a c compiler usually with the flag -funroll-loops. The main issue is that you don't always know at compile time how many iterations you are going to need, so compilers have to be able to handle the general case correctly. If a compiler can determine that the number of loop iterations is invariant and the number of iterations is reasonably small, it will likely output machine code with the loops unrolled.
The other major issue is file size. If you know you'll have to iterate 1,000,000,000 times, unrolling that loop will make your executable binary huge.
精彩评论