On 8/13/2006 at 11:53 PM Sean Conner wrote:
for (i = 0 ; i < MAX ; i++)
foo[i] = 0;
when it could easily be replaced with:
memset(foo,0,sizeof(foo));
The argument some would give you is that if you had a compiler worth spit,
it would optimize away the index and reduce the above to:
memset(foo,0,sizeof foo);
i = MAX;
Then if the compiler saw that the value of i was re-initialized without
being read, it would get rid of the last statement. The explicit loop
statement is a easy way to explicitly state what's meant and does not rely
on the implementation of a library function.
One thing I've learned is "never underestimate the cleverness of a good
optimizer". If a loop is particularly complicated, you can occasionally
find an automatic optimization that's nothing short of pure genius.
We need to ask more of our compiler writers; we really do.
That's just the programmer not knowing the
available functions, or
perhaps, coming from a system that doesn't have stat() available (it's not
part of the ANSI-C standard library, limiting the ways one can get the
size
of a file portably, and each of them having problems).
For more horror
stories, you can always check out
http://thedailywtf.com/ .
Why not fseek( file, 0, SEEK_END); length = ftell( file); ?
ANSI-compatible and shouldn't involve any I/O.
Cheers,
Chuck