I'm so new. Please help me understand this part...
- My new Universal EA, come check it out.
- One trade per bar
- [ARCHIVE]Any rookie question, so as not to clutter up the forum. Professionals, don't pass it by. Can't go anywhere without you - 5.
I was under the impression that I could create a variable from inside a for loop and then use that variable outside the loop. That can't be done, can it?
No it cannot be done, if you create the variable inside the loop then it is only available to the loop.
If you create it outside the loop but inside the function that contains the loop then it will be available in throughout the function including the loop
and if you create it in the global space then it would be available everywhere.
//Here iVariable is available throughout the OnStart() function including the loop; void OnStart() { int iVariable = 0; for(int iC=0; iC<10; iC++) { iVariable = iC; } Print("iVariable = " + iVariable); } // here it will fail to compile because the Print statement has no access to iVariable void OnStart() { for(int iC=0; iC<10; iC++) { int iVariable = iC; } Print("iVariable = " + iVariable); } // here you get two iVariables one for the loop one for the OnStart() // the loop will use the locally declared iVariable // the Print statement will print 99 as it accesses the first iVariable void OnStart() { int iVariable = 99; for(int iC=0; iC<10; iC++) { int iVariable = iC; } Print("iVariable = " + iVariable); }
- www.mql5.com
I was under the impression that I could create a variable from inside a for loop and then use that variable outside the loop. That can't be done, can it?
Here is the documentation on variable visibility: Visibility Scope and Lifetime of Variables
And that is also a good search phrase for Google so you can learn more about variable scope and lifetime.
- docs.mql4.com