i++ FOR loop behaves differently from i-- for loop.. Is that a bug ?

 

I have an issue with the FOR loop while using on the object list...

Here a function to check object names and delete those whose names start with the text1 and text2 string... 

if I use  for(int i = ObjectsTotal(0) - 1; i >=0; i--)... the function works properly

but if I use  for(int i = 0; i < ObjectsTotal(0); i++)... the function leaves a lot of objects (not all though) that should be deleted... 

Looks like a bug or I may misunderstand something...  Any comments ? Does this behavior occurs also with others arrays ?

If that issue was already addressed somewhere, please  let me know where and accept my apologies...

 

void UnDraw()

  {

  string title;  

  //for(int i = 0; i < ObjectsTotal(0); i++)

  for(int i = ObjectsTotal(0) - 1; i >=0; i--)

    {

    title = ObjectName(0, i);

    if(StringFind(title, "text1")   >= 0) ObjectDelete(0, title);

    if(StringFind(title, "text2")   >= 0) ObjectDelete(0, title);    

    }

  Print("Number of object AFTER deleting: ", ObjectsTotal(0));

  return; 

  } 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Objects Constants / Object Properties
Documentation on MQL5: Standard Constants, Enumerations and Structures / Objects Constants / Object Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Objects Constants / Object Properties - Documentation on MQL5
 

It's not a bug. Think about what's happening:

You have a list of objects

Object numberObject Name
0Object 1
1Object 2
2Object 3

 

During your ++ loop you delete number 0 first so i = 0 and here's what the list will look like after:


Object numberObject Name
0Object 2
1Object 3

  

 The object numbers has been updated but i still = 0. The next time it loops i will = 1 so it will delete "Object 3". Now that loop is finished i will = 2 which is greater than the amount of objects so the loop breaks and Object 2 is left not deleted.

If you did it counting down then it will always be deleting the last object in the list and it won't matter that the list has updated. 

Hope this helped 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Objects Constants / Object Properties
Documentation on MQL5: Standard Constants, Enumerations and Structures / Objects Constants / Object Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Objects Constants / Object Properties - Documentation on MQL5
 

Good answer hellflip43, always count down to zero. Many user think, count down from top to bottom, it should be count down to zero.

And FXDub, next time please use SRC button to post your code 

 

 

@Heelflip43   Aaaaaaaaaaaah ... Of course !!! I did not think the good way... Thanks a bunch... Now it's crystal clear... 

@phi.nuts     Sure... I'll format the code next time... That was my first post here and posting in quite a hurry, I did not pay attention .. sorry.. 

 

 

Reason: