Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

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

The concept of function pointers in C and Unix systems. Function pointers allow for efficient and elegant function calls, runtime binding, and the ability to pass and return functions as arguments. why function pointers are used, how to define and use them, and provides examples using the qsort and bubblesort functions.

Typology: Exercises

2021/2022

Uploaded on 09/12/2022

ekaling
ekaling 🇺🇸

4.7

(39)

266 documents

1 / 16

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Function Pointers
15-123
Systems Skills in C and Unix
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

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