Assembly Language for Beginners

(nextflipdebug2) #1

1.27 Pointers to functions.


1.26.1 Fast square root calculation.


Another well-known algorithm wherefloatis interpreted as integer is fast calculation of square root.


Listing 1.362: The source code is taken from Wikipedia:http://go.yurichev.com/17364



  • and that int is 32 bits. /
    float sqrt_approx(float z)
    {
    int val_int =
    (int)&z; / Same bits, but as an int /
    /

  • To justify the following code, prove that



  • ((((val_int / 2^m) - b) / 2) + b) 2^m = ((val_int - 2^m) / 2) + ((b + 1) / 2) 2^m)



  • where



  • b = exponent bias

  • m = number of mantissa bits


  • .
    /




val_int -= 1 << 23; /* Subtract 2^m. */
val_int >>= 1; /* Divide by 2. */
val_int += 1 << 29; /* Add ((b + 1) / 2) * 2^m. */

return (float)&val_int; / Interpret again as float /
}


As an exercise, you can try to compile this function and to understand, how it works.


There is also well-known algorithm of fast calculation of√^1 x. Algorithm became popular, supposedly,


because it was used in Quake III Arena.


Algorithm description can be found in Wikipedia:http://go.yurichev.com/17360.


1.27 Pointers to functions


A pointer to a function, as any other pointer, is just the address of the function’s start in its code segment.


They are often used for calling callback functions^170.


Well-known examples are:



  • qsort()^171 ,atexit()^172 from the standard C library;

  • *NIX OS signals^173 ;

  • thread starting:CreateThread()(win32),pthread_create()(POSIX);

  • lots of win32 functions, likeEnumChildWindows()^174.

  • lots of places in the Linux kernel, for example the filesystem driver functions are called via callbacks:
    http://go.yurichev.com/17076

  • The GCC plugin functions are also called via callbacks:http://go.yurichev.com/17077

  • Another example of function pointers is a table in the “dwm” Linux window manager that defines
    shortcuts. Each shortcut has a corresponding function to call if a specific key is pressed:GitHub. As
    we can see, such table is easier to handle than a large switch() statement.


So, theqsort()function is an implementation of quicksort in the C/C++ standard library. The functions
is able to sort anything, any type of data, as long as you have a function to compare these two elements
andqsort()is able to call it.


(^170) wikipedia
(^171) wikipedia
(^172) http://go.yurichev.com/17073
(^173) wikipedia
(^174) MSDN

Free download pdf