Reputation: 99
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
Upvotes: 0
Views: 879
Reputation: 117298
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
}
Upvotes: 1
Reputation: 39513
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;
Upvotes: 1