473,657 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

for loop stop condition

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
Nov 14 '05 #1
3 2530
"Douglas" <mm***@yahoo.co .uk> wrote in message
news:4c******** *************** ***@posting.goo gle.com...
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 condition is fully evaluated every time. If you
want h+1 evaluated only once, then do that before
entering the loop and save it in a variable, then
use that variable for the condition.
Nov 14 '05 #2
xarax <xa***@email.co m> wrote:
"Douglas" <mm***@yahoo.co .uk> wrote in message
news:4c******** *************** ***@posting.goo gle.com...
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.
The condition is fully evaluated every time. If you
want h+1 evaluated only once, then do that before
entering the loop and save it in a variable, then
use that variable for the condition.


Can't a clever optimizing compiler determine, at least under some
circumstances (e.g. h ist never changed directly and isn't defined
as volatile and there are no changes done via pointers), that h can
not change it's value within the loop and than compare to 11 instead
of evaluation h+1 each time round?

At least a short look at the assembler produced by gcc for e.g.

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
int i, h;
h = 10;

for ( i = 0; i < h + 1; i++ )
printf( "%d\n", i );

return EXIT_SUCCESS;
}

looks a lot as if the comparison is done against the number 11 and not
the result of the calculation of h+1.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #3
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(i nt *);

void strange_func(in t 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.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #4

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

Similar topics

23
2193
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 = 5;
2
2676
by: Alex | last post by:
Compiler - Borland C++ 5.6.4 for Win32 Copyright (c) 1993, 2002 Borland Linker - Turbo Incremental Link 5.65 Copyright (c) 1997-2002 Borland Platform - Win32 (XP) Quite by accident I stumbled across some wierd loop behavior. With the pasted code I receive the output that follows. I realize that the code is broken, because the inner loop fails to reset j for each iteration of the outer loop (the fix is commented out). I also know that...
2
1189
by: Rvo | last post by:
I have written an application that manipulates files, while doing so the program is running in a loop and any actions on the GUI will not get any response. When I try to stop the processing of the files trough the GUI by clicking on a button this will not be done. The action connected to the stop-button is to set a boolean to "true" in the loop which processes the files I check contiuously for the boolean becomming true and if so exit...
3
3516
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, while the C# for loop ending condition is evaluated on every iteration." Is this accurate? I don't understand how you could get away without evaluating the ending condition at every iteration. Otherwise, how would you
8
2136
by: Jim Langston | last post by:
There's the thing about iterating though a map or vector when you may delete one of the elements, where you simply assign the iterator to the map.erase() statement or increment it if you don't. Well, I have this issue where I may delete the map element in 3 different places: for ( map_key_pcmissile::iterator mit = World.Missiles.begin(); mit != World.Missiles.end(); ) { if ( /* Some Condition */ )
16
3515
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 instructions which can sure be optimized away is the check for the break condition, at least within the time where it is known that the loop will not reach it. Any idea how to write such a loop? e.g.
8
12086
by: mtsweep | last post by:
Hi, I started a background thread to preform some time intensive tasks for a GUI frontend. This background thread uses a C++ object which requires a windows message loop so I started one in it by calling Application.Run(). Now I can see that messages from the C++ libraries are being processed. But how do I send my own messages to this thread from the GUI frontend? I tried to use delegates/events/etc but it ends up either spawning a...
3
11383
by: normadiah | last post by:
Dear all, I'm really appreciated if anyone can help me. I would like to ask regarding the following code... B]System.out.println("Enter Pre_condition or q to quit):"); while(condition.equalsIgnoreCase("q")==false) { condition = Input.nextLine(); if(condition.equalsIgnoreCase ("q")) break;
33
3043
by: dmoran21 | last post by:
Hi all, I am a mathematician and I'm trying to write a program to try out a formula that I've derived. However, it seems that I've got an infinite loop and I don't quite understand why. I was hoping someone could point me in the right direction. Code: #include <stdio.h> #include <math.h>
0
8425
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8326
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8743
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.