On 10 Jul 2004 10:23:21 -0700,
mm***@yahoo.co.uk (Douglas) wrote in
comp.lang.c:
Hi,
In the loop
for(i=0; i< h+1; i++);
if h=10 say, then is h+1 evaluated every time or, between iterations,
does the for loop remember that the condition i<11 is being applied?
I'm guessing that it evaluates every time as it is possible that h may
have been changed by the body of the loop.
Douglas
The C abstract machine requires evaluation of the condition each time,
but the "as-if" rule allows it to be optimized away if the compiler
can analyze the code and determine that it is not modified in the loop
body.
This is called "loop invariant code hoisting", and is a very common
optimization technique used by compilers.
Consider:
void blank_lines(int x)
{
int i;
for (i = 0; i < x+1; ++i)
{
putchar('\n');
}
}
Since x is automatic, is not defined as volatile, is not modified
within the loop, and its address is not passed to a function, the
compiler can tell that it cannot be modified within the loop, so it
can optimize the calculation away.
On the other hand, given:
void stranger_func(int *);
void strange_func(int x)
{
int i;
for (i = 0; i < x+1; ++i)
{
stranger_func(&x);
}
}
Here, especially if the definition of stranger_func() is another
source file, the compiler cannot assume that the value of x remains
constant throughout the loop, and must calculate x+1 each time.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html