very simple, is there any speed or memory diference beetwen this two whiles?

int x = 0, y = 0;
while(x < size)
{
             y++;
             array[x] = array[y];
             x++;
}

and

int x = 0;
while(x < size)
{
             array[x] = array[x++];
}

Recommended Answers

All 3 Replies

You seem to be trying to shift array elements 1 element to the left.

The second version is a better concept, but doesn't work how you think. The net result is no change, you'll just be copying the contents of an element back into itself. There is no change, because the left side of the assignment isn't evaluated until after the right side. As a result the x on the left is now the new value of (x+1), not its original value, which results in copying a block of memory back in to itself.

You want something more like:

int x = 0;
while(x < size)
{
  array[x] = array[x+1];
  x++
}

This version is more efficient than the first version. It uses less memory (specifically, 32-bits less) and the CPU doesn't have to touch the memory as much. It also references 2 different blocks of memory because of the way the addition is performed. This version does not modify x until after the data copy has taken place.

commented: just what i needed it +1

First: The second one doesn't do the same thing as the first one.
Second: Try this if you want to shift the elements:

int intX = 0;
while (intX != intSize) {
  array[ intX ] = array[ intX + 1 ];
  ++intX;
}

Note! If speed is that much a concern for you:
++intX is much faster than intX++
If you want to iterate through an array up to a position strictly less than intSize: use intX != intSize - intX < intSize is more expensive

thanks for both replys... I think I''ll go with

int intX = 0;
while (intX != intSize)
 {
      array[ intX ] = array[ intX + 1 ];
      ++intX;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.