473,387 Members | 1,532 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

For loop condition evaluation

I have several questions.

In C, AFAIU, a for loop is just syntactic sugar for a while loop.

for (i1; i2; i3) i4;

is equivalent to

i1
while (i2) {
i4;
i3;
}

Now, assume I have the following:

for (i=0; i<foo(); ++i) bar();

If I understand correctly, foo() will be evaluated for every
iteration of the loop, EVEN IF the result does not depend on i?

If I recall correctly, the termination condition is evaluated only
once in some languages such as Pascal.

Is it my responsability to do:

n = foo();
for (i=0; i<n; ++i) bar();

to tell the compiler NOT TO evaluate foo() every iteration since I
know it is invariant?

Do optimizing compilers figure it out by themselves?

What if the termination condition is:

for (i=0; i<p->n; ++i) bar();

Will I similarly pay for one pointer dereferencing every iteration
and should I write instead:

n = p->n;
for (i=0; i<n; ++i) bar();

Thanks to all who care to reply!

Nov 13 '05 #1
6 11047
Shill wrote:
I have several questions.

In C, AFAIU, a for loop is just syntactic sugar for a while loop.

for (i1; i2; i3) i4;

is equivalent to

i1
while (i2) {
i4;
i3;
}
Almost. Pedants would make that:

do {
i1;
while (i2)
{
i4;
i3;
}
} while (0);

Because it behaves the same when used as the single statement between an
if and an else.
Now, assume I have the following:

for (i=0; i<foo(); ++i) bar();

If I understand correctly, foo() will be evaluated for every
iteration of the loop, EVEN IF the result does not depend on i?
Probably. Unless the compiler can work out that foo() does not depend
on i in any way it will have to evaluate it every time.

Since you usually use a for loop to go through a sequence of things
using pointers, this usually means that the compiler must know that
foo() does not access any area of memory that the body of the loop accesses.

The other question is how foo() bahaves in relation to globals -- if it
modifies any global, the compiler must invoke it every time to maintain
the correct semantics.
Is it my responsability to do:

n = foo();
for (i=0; i<n; ++i) bar();

to tell the compiler NOT TO evaluate foo() every iteration since I
know it is invariant?

Do optimizing compilers figure it out by themselves?
As you say, there are two approaches to this:

1: Help the compiler figure out it's invariant. If you have a C99-ish
compilation environment, you can use restrict pointers where appropriate
to help here. However, this may not help unless the compiler can see
the code of foo() -- if it's in another object file it can't determine
the effect on globals.

2: Just do it yourself.

Personally, I would try approach 1 firat, and swith to 2 when(!) it
doesn't work.
What if the termination condition is:

for (i=0; i<p->n; ++i) bar();

Will I similarly pay for one pointer dereferencing every iteration
Yes, unless you have a very good compiler. However, making p a restrict
pointer will definitely help in this case -- it should optimise away the
dereference (provided the compiler heuristics feel it's worth it).
and should I write instead:

n = p->n;
for (i=0; i<n; ++i) bar();


If you're that bothered about eliminating a the pointer dereference,
then this is the only way to guarantee it. However I would suggest that
you check wheter the speed gain is significant -- assuming stuff's still
in a core-speed cache, you're only looking at a 1-3 cycle saving by
eliminating the dereference. For most systems you won't be able to
measure this unless your loop is very short.

It's probably worth eliminating the function calls, but I would make the
pointer dereference decision based on which method is morereadable
rather than which is theoretically faster.

Regards,

Phil

Nov 13 '05 #2
Shill wrote:

I have several questions.

In C, AFAIU, a for loop is just syntactic sugar for a while loop.
The meaning of "break" is slightly different for "for" and "while"
for (i=0; i<foo(); ++i) bar();

If I understand correctly, foo() will be evaluated for every
iteration of the loop, EVEN IF the result does not depend on i?
Yes.
Is it my responsability to do:

n = foo();
for (i=0; i<n; ++i) bar();

to tell the compiler NOT TO evaluate foo() every iteration since I
know it is invariant?
Yes.
Do optimizing compilers figure it out by themselves?
An optimizing compiler is allowed to do
whatever it takes to produce a program with correct behavior,
but I wouldn't expect that much figuring
to be within the capabilities of a compiler.

What if the termination condition is:

for (i=0; i<p->n; ++i) bar();

Will I similarly pay for one pointer dereferencing every iteration
and should I write instead:

n = p->n;
for (i=0; i<n; ++i) bar();


You'd have to time it and know that your time results are
implementation dependant.

--
pete
Nov 13 '05 #3
# for (i=0; i<foo(); ++i) bar();
#
# If I understand correctly, foo() will be evaluated for every
# iteration of the loop, EVEN IF the result does not depend on i?

If it is invariant and free of visible side effects, you can't tell if it's
evaluated once or with every iteration. If the optimiser can prove the
predicate is such, the optimiser is free to move all the evaluation outside
the loop.

# Is it my responsability to do:
#
# n = foo();
# for (i=0; i<n; ++i) bar();
#
# to tell the compiler NOT TO evaluate foo() every iteration since I
# know it is invariant?

If you want to guarentee the invariant code is moved out of the loop,
and your compiler does not provide that guarentee.

# Do optimizing compilers figure it out by themselves?

Depends. On whether it can analyze the predicate. Whether you asked it
to. Whether the compiler writer added the analysis.

# What if the termination condition is:
#
# for (i=0; i<p->n; ++i) bar();
#
# Will I similarly pay for one pointer dereferencing every iteration
# and should I write instead:

Optimisers deal with expressions in general. So it will deal as it can
with functions and pointers and anything else.

--
Derk Gwen http://derkgwen.250free.com/html/index.html
This is one wacky game show.
Nov 13 '05 #4
Shill <no****@example.com> wrote:
I have several questions.

In C, AFAIU, a for loop is just syntactic sugar for a while loop.

for (i1; i2; i3) i4;

is equivalent to

i1
while (i2) {
i4;
i3;
}
There is one important difference - if any part of the loop body
executes a continue; statement, the for loop will execute i3 before
testing i2, but the while loop version won't - it jumps straight to the
test.
Now, assume I have the following:

for (i=0; i<foo(); ++i) bar();

If I understand correctly, foo() will be evaluated for every
iteration of the loop, EVEN IF the result does not depend on i?

If I recall correctly, the termination condition is evaluated only
once in some languages such as Pascal.

Is it my responsability to do:

n = foo();
for (i=0; i<n; ++i) bar();

to tell the compiler NOT TO evaluate foo() every iteration since I
know it is invariant?
That's the only way to be certain.
Do optimizing compilers figure it out by themselves?
Some might - especially with standard library functions like strlen,
which the compiler knows more about than a general function written by
the user.
What if the termination condition is:

for (i=0; i<p->n; ++i) bar();

Will I similarly pay for one pointer dereferencing every iteration
and should I write instead:

n = p->n;
for (i=0; i<n; ++i) bar();


This is more of a microoptimisation - you really shouldn't do this
unless profiling shows that the dereference is having a measurable
effect on program speed - and make sure you test before and after,
because it's conceivable that this "optimisation" could actually make
the complete function *slower* - because you're now using one extra
variable, you may have caused an extra spill of a register-held variable
into memory...

- Kevin.

Nov 13 '05 #5
"pete" <pf*****@mindspring.com> wrote in message
news:3F**********@mindspring.com...
| Shill wrote:
| >
| > In C, AFAIU, a for loop is just syntactic sugar for a while loop.
|
| The meaning of "break" is slightly different for "for" and "while"

"break" is the same, it is actually "continue" that has a different
meaning: in the case of a for loop, the increment statement will
be executed before moving on to the next iteration.

Regards,
Ivan

--
http://www.post1.com/~ivec
Nov 13 '05 #6
Ivan Vecerina wrote:

"pete" <pf*****@mindspring.com> wrote in message
news:3F**********@mindspring.com...
| Shill wrote:
| >
| > In C, AFAIU, a for loop is just syntactic sugar for a while loop.
|
| The meaning of "break" is slightly different for "for" and "while"

"break" is the same, it is actually "continue" that has a different
meaning: in the case of a for loop, the increment statement will
be executed before moving on to the next iteration.


Sorry about that.
Thank you.

--
pete
Nov 13 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: Mark Anderson | last post by:
A 'for' loop takes 3 arguments (initialize; test; increment). The 'test' must equate as true or false This doesn't work... x = 5; for (y=1; (y==5); y+=1) { alert(x * y); } ...nor does... x...
2
by: smauldin | last post by:
Why does the execution plan have a nested loop join for a simple select with an UDF in the where clause? Here is the query: select * from test_plan where vCol = my_udf('test') Here is the...
3
by: Douglas | last post by:
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...
3
by: Ben R. | last post by:
In an article I was reading (http://www.ftponline.com/vsm/2005_06/magazine/columns/desktopdeveloper/), I read the following: "The ending condition of a VB.NET for loop is evaluated only once,...
7
by: gmou | last post by:
Dear group, I am building a translator from C++ into VB (and into C#). At the moment, I have a hard time figuring out the equivalent of a 'for' loop in VB. Given C++ code: for( int i=0;...
34
by: Frederick Gotham | last post by:
Is the domestic usage of the C "for" loop inefficient when it comes to simple incrementation? Here's a very simple program that prints out the bit-numbers in a byte. #include <stdio.h> #include...
7
by: dis_is_eagle | last post by:
hi..i have a question on the execution of for loop...i think the order of execution of the for loop is initialization,condition and increment...but i couldnt understand the following questions.......
16
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of...
44
by: James Watt | last post by:
can anyone tell me how to do an infinite loop in C/C++, please ? this is not a homework question .
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.