I got into an argument with a co-worker today about this snippet:
for (int i = 0; i < foo(); i++)
{
}
I told him that he shouldn't put the foo() function in the termination check of that for loop. He said that the compiler actually assigns the result of foo() to a variable and then sticks that in where foo() is at. I said that we can't rely on that. We're working in C++ on .NET. Who's right?
Name:
Anonymous2009-02-28 2:32
>>1
Assuming that foo() is a pure function, then he should assign the result to a variable and then test against that variable, otherwise the function will get called repeatedly for no reason. If foo() is impure, however, then you need to keep the function call within the condition.
if you were using C with a decent compiler (or even gcc), you could mark the function as a pure function and the compiler would automatically save the result.
Name:
Anonymous2009-02-28 2:52
>>3
How can the compiler save the result at compile time? It has to execute the function, right?
You are both wrong. It will not save foo() unless it is simple enough for the compiler to tell that it is pure. However, arguing over optimization here is pointless because a) you are initializing i inside the loop anyway, so I doubt the program is time critical, or even time neccesary to the extent where something like this would matter (or you are just immense faggots who shouldn't be trying to optimize anyway because you will do it in all the wrong places protip: run a speed diagnostic and find bottlenecks, don't jew around over insignificant shit. And then b) You are programming for .NET so speed is again, obviously a non-issue. The time cost associated with you both wasting time thinking about this was not worth it's own weight; and you are effectively costing your employer money. Go and do something productive.
Name:
FrozenVoid2009-02-28 3:00
>>1
The call to foo() is performed every iteration, as if was String.length or Object.property.
Unless the iterator is connected to foo() you should use it. use
x=foo() and then compare i<x
>>5 You are both wrong. It will not save foo() unless it is simple enough for the compiler to tell that it is pure.
lrn2read: you could mark the function as a pure function
>>4 >>3 didn't say anything about doing it at compile time. the compiler can generate code to save the result and reuse it instead of generating code to call the function each time.
Name:
Anonymous2009-02-28 3:31
>>7
I meant OP and his friend were both wrong, faggot.
>>13
See: http://4-ch.net/code/index.html look under "Programming @4-ch" at the top. Ignore the idiots saying you've been trolled, they're just being juvenile.
Name:
Anonymous2009-02-28 12:41
Why the hell would you get into an argument over this? Just write some test code and shut up about it.
Name:
Anonymous2009-02-28 22:19
Why the hell would you get into an argument about this? The answer is obvious.