简体   繁体   中英

How to get the last index in a for loop

i am coding in a language similar to c++ known as mql5.(for mt5 trading platform) they have many similarities... i have a for loop as shown below:

void OnTick()  // this functon basically executes the code after every price change.
{
   for (int i = 0; i<5; i++)  //the for loop function
    {
     Print(i);  //this prints the loop
    }
}

the result of the code above with each price change overtime is:

13:27:18.706    0
13:27:18.706    1
13:27:18.706    2
13:27:18.706    3
13:27:18.706    4

13:27:18.900    0
13:27:18.900    1
13:27:18.900    2
13:27:18.900    3
13:27:18.900    4

question is, how do i access the last element in the index of the for loop and get it to print 4th index each time price changes? mql5 is somewhat similar as c++. is there anything i can carry from c++?

eg

13:27:18.706    4
13:27:18.900    4

All you need to do is pull i outside the loop:

void OnTick()
{
   int i = 0;
   for (; i < 5; i++)
   {
     Print(i);
   }
   // i is now one past the last index
   int last = i - 1;
}

If you know that you loop 5 times in advance, you could also obtain the last index using:

int last = 5 - 1;

Don't use magic numbers. 5 is a magic number. Give it a meaningful name, like number_of_prices .

constexpr size_t number_of_prices = 5;

void OnTick()
{
    for (size_t i = 0; i < number_of_prices; ++i)  //the for loop function
    {
        Print(i);  //this prints the loop
    }
    Print(number_of_prices - 1); // access last price
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM