Docsity

Function Pointers: Efficient and Elegant Way to Pass and Return Functions, Exercises of Object Oriented Programming

Partial preview of the text

Download Function Pointers: Efficient and Elegant Way to Pass and Return Functions and more Exercises Object Oriented Programming in PDF only on Docsity!

Function Pointers

Systems Skills in C and Unix

Code and Data

int foo( ){

} int main (int argc, char* argv[]) {

foo() ; ……

CODE

DATA

main

foo

main:.LFB6:

pushq

%rbp

.LCFI2:

movq

%rsp, %rbp

.LCFI3:

subq

$32, %rsp

.LCFI4:

movl

%edi, -20(%rbp)

movq

%rsi, -32(%rbp)

movl

$10, -4(%rbp)

movl

-4(%rbp), %edi

call

foo

leaveret

Assembly code

Why use function pointers?

Efficiency

Elegance

Runtime binding

Determine sorting function based on type of dataat run time

Eg: insertion sort for smaller data sets (n <100)

Eg: Quicksort for large data sets ( n > 100000)

Other sorting algorithms based on type of data set

Defining a function pointer

int (fn)(int,int) ;typedef int (Ptr)(int,int) ;

Functions that return function pointers

typedef int (*Ptr)(int,int);

qsort

A unix utility function that can be used to sortany data set stored in an array (really cool!!)

Using qsort

An array of char *’s

A

guna

andy

me

Write the compare function to sort by alpha orderInt (*strcomp)(const void * a, const void * b))

Using qsort An array of node *’s

A

Guna

Andy

Me

Write the compare function to sort by name:int (*nodecomp)(const void * a, const void * b))

Sorting an 2D array of char’s

Generic Bubble sort with

function pointers

typedef int (cmp)(const void, int , int);typedef int (swap)(void, int, int); int bubblesort(void* A, int n, cmp cfn, swap sfn){

int i, j;for (i=0;i<n-1; i++)

for (j=0; j<n-i-1; j++)

if (cfn(A, j, j+1)>0)

sfn(A, j, j+1);

Coding Examples