Can "return" operator exit loop in user-defined function and return the required value?

 

Can "return" operator exit loop in user-defined function and return the required value? or there is no way but to use "break" operator to exit the loop and then "return" operator to terminate the function and get the required value?


Thanks 

 
Michael: Can "return" operator exit loop in user-defined function and return the required value? or there is no way but to use "break" operator to exit the loop and then "return" operator to terminate the function and get the required value?

Yes, "return" in a loop will return from the function and return a value if necessary and defined as such!

Before asking, did you consider just trying it out and experimenting with it?

 
Fernando Carreiro:

Yes, "return" in a loop will return from the function and return a value if necessary and defined as such!

Before asking, did you consider just trying it out and experimenting with it?

Yes I did tried it out, and the function worked fine only when I used "break" then "return" but returned nothing when I used "return" alone and I am trying to figure out why

 
Michael: Yes I did tried it out, and the function worked fine only when I used "break" then "return" but returned nothing when I used "return" alone and I am trying to figure out why

Show your code then so we can help you identify the problem!

 

Example Script code and output:

void OnStart()
{
   PrintFormat( "Test return value: %d", TestReturn() );
}

int TestReturn(void)
{
   for( int i = 1; i < 10; i++ )
   {
      if( i == 3 ) return i;
   }
   
   return 0;
}
2021.05.23 11:25:48.593 TestReturn (EURUSD,H1)  Test return value: 3