May 22, 2024, 04:55:40 AM

## News:

IonicWind Snippit Manager 2.xx Released!  Install it on a memory stick and take it with you!  With or without IWBasic!

## Function pointers

Started by Parker, February 11, 2006, 11:16:36 PM

0 Members and 1 Guest are viewing this topic.

#### Parker

##### February 11, 2006, 11:16:36 PM
Now that we have function pointers, I thought I'd show a use for them. I'm not going to present a full calculator/expression evaluator here, but imagine that you have one, and it has an option for either degrees or radians. In Aurora the SIN() function returns radians, and the SIND() function returns degrees. So one way to handle that option is
`// Imagine this select block is handling the keywordscase "SIN":    if (mode = RADIANS) return SIN(param(0)) else return SIND(param(0));case "MODE":    if (param(0) = "RADIANS") mode = RADIANS else mode = DEGREES;`
Which works fine, but if you're doing intense operations, you don't want the overhead of an IF statement each time a function is called. So you can use function pointers.
`declare *mysin(double d),double;...// In the keyword select blockcase "SIN":    return mysin(param(0));case "MODE":    if (param(0) = "RADIANS") mysin = &SIN else mysin = &SIND;`

Whenever mysin() is called, the compiler does an implicit dereference, like it does with imported functions. So when mysin holds the address of SIN(), when it is dereferenced and called it will call SIN. The same goes for SIND, or any other function taking a double parameter and returning a double. You must be careful though to not assign that pointer to anything else, because it most probably will result in a crash.

Using function pointers eliminates the extra code that must be executed for the IF statement, which slows down your code not only by the obvious way, but code tends to run much faster when there are fewer comparison statements since the processor can't very well predict the path of execution when it has to guess what the result of the compare will be in advance.