Hi
I checked the following two programs with DDD(digital dispaly
debugger on linux). In for loop, the index variable i is always kept
in EAX
register but in while loop it was kept in EAX register only at the
time where the actual use of index variable(i.e at the time of
incrementing index
variable) and after the increment some other variable using EAX
register. In next iteration variable i is stored back to EAX.
There may be a case that the compiler(will told ahead of time that
increment index variable with each iteration)knows ,ahead of the time,
that the index variable in for loop will be incremented with each
iteration. where as in While loop the incrementing index variable is
known at end of the body the while.
And the compiler won't tell that this index variable will always be
incremented
with each iteration.
So from the above experiment for loop executes faster than while loop.
The above conclusion is based on the assumtion that the register
access is
faster than memory access.
--------------------------------------------------------------------
for.c
-----------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,n=10,sum=0;
for(i = 0; i < n; i++)
{
sum += i;
}
}
----------------------------------------------------------------------------
while.c
--------------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,n=10,sum=0;
i=0;
while(i < n)
{
sum += i;
i++;
}
}
~--------------------------------------------------------------------------------------
CBFalconer <cb********@yahoo.com> wrote in message news:<41***************@yahoo.com>...
"Mahesh Kumar Reddy.R" wrote:
Can any body resolve this..
In what cases one of the loop constructs better than other
interms of speed , space and any other (redability).
No.