User Defined Functions

 
I'm "still learning" how to program and wanted to create and use a User Defined Function, however I guess I don't understand how to do this. I am modifying an indicator which uses the following code mulitple times. I thought it best to create a function and call it rather than duplicate these lines of code 5 or 6 times..

RangeLimit = High[i];
for ( j = i - 7 ; j < i + 7 ; j++)
{
if (High[j] > RangeLimit)
{
RangeLimit = High[j];
}
}

I tired to create a function like this but keep getting "function definition unexpected"..

int FindRange( int x)
{
RangeLimit = High[x];
for ( j = x - 7 ; j < x + 7 ; j++)
{
if (High[j] > RangeLimit)
{
RangeLimit = High[j];
}
}
return(RangeLimit);
}


would someone mind teaching a newbie how to do this correctly...

thanks in advance

david
 
You probably put the function inside another or accidentally left out one of the curly brackets in the function above. However, I see a couple of things. The return value RangeLimit should be defined inside the function, not as a global variable. Also it should be a double, not an int.

Something like this:
int start()
{
   ....


   RangeLimit= FindRange(i);

   ...

}


double FindRange( int x)
{
   double rl;   // define variables used in a function inside that
   int j;    // function so they don't mix with the rest of the program

   rl= High[x];
   for ( j = x - 7 ; j < x + 7 ; j++)
   {
      if (High[j] > rl)
      {
         rl= High[j];
      }
   }

   return(rl);
}




Or alternately (I'm just showing off here, please bear with me, grin)

double FindRange(int x)
{
   double rl= 0;  // 0 won't be able to remain max value with prices
   for (int j = x - 7 ; j < x + 7 ; j++)
   {
      rl= MathMax(rl, High[x]);
   }
   return rl;
}




But the idea of a newbie putting repeated code into a function shows much promise ... with that mindset you'll soon become a proficient programmer!



Markus

 
Markus,


thanks for the input.. Great catch about returning double, I don't know why, but I was thinking I'd return the bar when I should have been returning the price...Silly me...

Anyway, I tried what you suggested, but I guess I'm still not gettting it as I got the same error message.. Would you mind if I sent you the indicator and let you modify it..

Thanks in advance..

d
 
David,

just mail it to m.schmidt@emtec.com



Markus
Reason: