pointers to functions in c programming language. introduction while many programming languages...

22
Pointers to Pointers to Functions Functions In C programming language In C programming language

Upload: natalie-owens

Post on 02-Jan-2016

226 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Pointers to FunctionsPointers to Functions

In C programming languageIn C programming language

Page 2: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

IntroductionIntroduction

While many programming languages support the While many programming languages support the concept of pointers to data, only a few enable concept of pointers to data, only a few enable you to define pointers to code -- that is, pointers you to define pointers to code -- that is, pointers that point to functions.that point to functions.

Originally introduced in C, pointers to functions Originally introduced in C, pointers to functions are widely used in C++are widely used in C++

Unfortunately, their cumbersome syntax baffles Unfortunately, their cumbersome syntax baffles both novices and experienced programmers. both novices and experienced programmers.

Page 3: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

What are function Pointers?What are function Pointers?

C does not require that pointers only point C does not require that pointers only point to data, it is possible to have pointers to to data, it is possible to have pointers to functionsfunctions

Functions occupy memory locations Functions occupy memory locations therefore every function has an address therefore every function has an address just like each variablejust like each variable

Page 4: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Why do we need function Why do we need function Pointers?Pointers?

Useful when alternative functions maybe Useful when alternative functions maybe used to perform similar tasks on data (eg used to perform similar tasks on data (eg sorting)sorting)

One common use is in passing a function One common use is in passing a function as a parameter in a function call.as a parameter in a function call.

Can pass the data and the function to be Can pass the data and the function to be used to some control functionused to some control function

Greater flexibility and better code reuseGreater flexibility and better code reuse

Page 5: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Define a Function PointerDefine a Function Pointer

A function pointer is nothing else than a variable, A function pointer is nothing else than a variable, it must be defined as usual.it must be defined as usual.

Eg,Eg,

int (*funcPointer) (int, char, int);int (*funcPointer) (int, char, int);

funcPointer is a pointer to a function.funcPointer is a pointer to a function. The extra parentheses around (*funcPointer) is The extra parentheses around (*funcPointer) is

needed because there are precedence needed because there are precedence relationships in declaration just as there are in relationships in declaration just as there are in expressions expressions

Page 6: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Assign an address to a Function Assign an address to a Function PointerPointer

It is optional to use the address operator & It is optional to use the address operator & infront of the function’s nameinfront of the function’s name

When you mention the name of a function but When you mention the name of a function but are not calling it, there’s nothing else you could are not calling it, there’s nothing else you could possibly be trying to do except for generating a possibly be trying to do except for generating a pointer to itpointer to it

Similar to the fact that a pointer to the first Similar to the fact that a pointer to the first element of an array is generated automatically element of an array is generated automatically when an array appears in an expressionwhen an array appears in an expression

Page 7: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Assign an address to a Function Assign an address to a Function PointerPointer

//assign an address to the function pointer//assign an address to the function pointerint (*funcPointer) (int, char, int);int (*funcPointer) (int, char, int);

int firstExample ( int a, char b, int c){int firstExample ( int a, char b, int c){ printf(“ Welcome to the first example”);printf(“ Welcome to the first example”); return a+b+c;return a+b+c;}}funcPointer= firstExample; //assignmentfuncPointer= firstExample; //assignmentfuncPointer=&firstExample; //alternative using funcPointer=&firstExample; //alternative using

address operatoraddress operator

Page 8: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Comparing Function PointersComparing Function Pointers

Can use the (==) operatorCan use the (==) operator

//comparing function pointers//comparing function pointers

If (funcPointer == &firstExample)If (funcPointer == &firstExample)

printf (“pointer points to firstExample”);printf (“pointer points to firstExample”);

Page 9: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Calling a function using a Calling a function using a Function PointerFunction Pointer

There are two alternativesThere are two alternatives

1)1) Use the name of the function pointerUse the name of the function pointer

2)2) Can explicitly dereference itCan explicitly dereference it

int (*funcPointer) (int, char, int);int (*funcPointer) (int, char, int);

// calling a function using function pointer// calling a function using function pointer

int answer= funcPointer (7, ’A’ , 2 );int answer= funcPointer (7, ’A’ , 2 );

int answer=(* funcPointer) (7, ’A’ , 2 );int answer=(* funcPointer) (7, ’A’ , 2 );

Page 10: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Arrays of Function PointersArrays of Function Pointers C treats pointers to functions just like pointers to C treats pointers to functions just like pointers to

data therefore we can have arrays of pointers to data therefore we can have arrays of pointers to functionsfunctions

This offers the possibility to select a function This offers the possibility to select a function using an indexusing an index

Eg.Eg. suppose that we’re writing a program that displays suppose that we’re writing a program that displays

a menu of commands for the user to choose a menu of commands for the user to choose from. We can write functions that implement from. We can write functions that implement these commands, then store pointers to the these commands, then store pointers to the functions in an array:functions in an array:

Page 11: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

void (*file_cmd[]) (void) = void (*file_cmd[]) (void) = { { new_cmd, new_cmd,

open_cmd, open_cmd, close_cmd, close_cmd, save_cmd , save_cmd , save_as_cmd,save_as_cmd,

print_cmd,print_cmd, exit_cmdexit_cmd};};

If the user selects a command between 0 and 6, then we can subscript the If the user selects a command between 0 and 6, then we can subscript the file_cmd array to find out which function to callfile_cmd array to find out which function to call

file_cmd[n]();file_cmd[n]();

Page 12: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Trigonometric FunctionsTrigonometric Functions// prints tables showing the values of cos,sin // prints tables showing the values of cos,sin #include <math.h>#include <math.h>#include <stdio.h>#include <stdio.h>void tabulate(double (*f)(double), double first, double last, double incr);void tabulate(double (*f)(double), double first, double last, double incr);main()main(){{double final, increment, initial;double final, increment, initial;

printf (“Enter initial value: “);printf (“Enter initial value: “);scanf (“%lf”, &initial);scanf (“%lf”, &initial);

printf (“Enter final value: “);printf (“Enter final value: “);scanf (%lf”, &final);scanf (%lf”, &final);

printf (“Enter increment : “);printf (“Enter increment : “);scanf (%lf”, &increment);scanf (%lf”, &increment);

Printf(“\n x cos(x) \n”Printf(“\n x cos(x) \n” “ “ ---------- -----------\n”);---------- -----------\n”);tabulate(cos, initial,final,increment);tabulate(cos, initial,final,increment);

Printf(“\n x sin (x) \n”Printf(“\n x sin (x) \n”“ “ ---------- -----------\n”);---------- -----------\n”);

tabulate(sin, initial,final,increment);tabulate(sin, initial,final,increment);

return 0;return 0;}}

Page 13: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Trigonometric FunctionsTrigonometric Functions// when passed a pointer f prints a table showing the value of f// when passed a pointer f prints a table showing the value of fvoid tabulate(double (*f) (double), double first, double last, double void tabulate(double (*f) (double), double first, double last, double

incr)incr){{

double x;double x;int i, num_intervals;int i, num_intervals;num_intervals = ceil ( (last -first) /incr );num_intervals = ceil ( (last -first) /incr );for (i=0; i<=num_intervals; i++){for (i=0; i<=num_intervals; i++){

x= first +i * incr;x= first +i * incr;printf(“%10.5f %10.5f\n”, x , (*f) (x));printf(“%10.5f %10.5f\n”, x , (*f) (x));

}}}}

Page 14: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Enter initial value: 0Enter initial value: 0Enter final value: .5Enter final value: .5Enter increment: .1Enter increment: .1

XX cos(x)cos(x)-------- ---------------- ----------------------0.000000.00000 1.000001.000000.100000.10000 0.995000.995000.200000.20000 0.980070.980070.300000.30000 0.955340.955340.400000.40000 0.921060.921060.500000.50000 0.877580.87758

XX sin(x)sin(x)-------- ---------------- ----------------------0.000000.00000 0.000000.000000.100000.10000 0.099830.099830.200000.20000 0.198670.198670.300000.30000 0.295520.295520.400000.40000 0.389420.389420.500000.50000 0.479430.47943

Page 15: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

SortingSorting Consists of three partsConsists of three parts1)1) a comparison that determines the ordering of any pair of objectsa comparison that determines the ordering of any pair of objects2)2) an exchange that reverses their orderan exchange that reverses their order3)3) A sorting algorithm that makes comparisons and exchange until the objects are in A sorting algorithm that makes comparisons and exchange until the objects are in

order.order.<the sorting algorithm is independent of the comparison and exchange operator><the sorting algorithm is independent of the comparison and exchange operator>

qsortqsort will sort an array of elements. This is a wild function that uses a pointer to will sort an array of elements. This is a wild function that uses a pointer to another function that performs the required comparisons. another function that performs the required comparisons.

Library: stdlib.h Prototype:Library: stdlib.h Prototype:

void qsort ( void *base , size_t num , size_t size , int (*comp_func) (const void *, const void void qsort ( void *base , size_t num , size_t size , int (*comp_func) (const void *, const void *))*))

Some explanation.Some explanation. void * base is a pointer to the array to be sorted. This can be a pointer to any data type void * base is a pointer to the array to be sorted. This can be a pointer to any data type size_t num The number of elements. size_t num The number of elements. size_t size The element size. size_t size The element size. int (*comp_func)(const void *, const void *))This is a pointer to a function. int (*comp_func)(const void *, const void *))This is a pointer to a function.

Page 16: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

SortingSorting qsort thus maintains it's data type independence by giving the qsort thus maintains it's data type independence by giving the

comparison responsibility to the user. comparison responsibility to the user.

The compare function must return integer values according to the The compare function must return integer values according to the comparison result: comparison result:

less than zero : if first value is less than the second value less than zero : if first value is less than the second value zero : if first value is equal to the second value zero : if first value is equal to the second value greater than zero : if first value is greater than the second value greater than zero : if first value is greater than the second value

Some quite complicated data structures can be sorted in this Some quite complicated data structures can be sorted in this manner. manner.

The generic pointer type void * is used for the pointer arguments, The generic pointer type void * is used for the pointer arguments, any pointer can be cast to void * and back again without loss of any pointer can be cast to void * and back again without loss of information.information.

Page 17: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

qsortqsort#include <stdio.h>#include <stdio.h>#define NSTRS 10 /* number of strings */ #define NSTRS 10 /* number of strings */ #define STRLEN 16 /* length of each string */ #define STRLEN 16 /* length of each string */ char strs [NSTRS] [STRLEN]; /* array of strings */ char strs [NSTRS] [STRLEN]; /* array of strings */ main() { main() { int i; int i; extern int compare1(), compare2(); extern int compare1(), compare2();

/* Prompt the user for NSTRS strings. */ /* Prompt the user for NSTRS strings. */ for (i = 0; i < NSTRS; i++) for (i = 0; i < NSTRS; i++) { printf ("Enter string #%d: ", i); { printf ("Enter string #%d: ", i);

gets(strs[i]);gets(strs[i]);}}

Page 18: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

qsortqsort/* * Sort the strings into ascending order. /* * Sort the strings into ascending order.

There are NSTRS array elements, each one is STRLEN characters long.*/There are NSTRS array elements, each one is STRLEN characters long.*/

qsort(strs, NSTRS, STRLEN, compare1); qsort(strs, NSTRS, STRLEN, compare1);

/* * Print the strings. */ /* * Print the strings. */ printf("\nSorted in ascending order:\n"); printf("\nSorted in ascending order:\n");

for (i = 0; i < NSTRS; i++) for (i = 0; i < NSTRS; i++) printf( "\t%s\n", strs[i] );printf( "\t%s\n", strs[i] );

/* * Now sort the strings in descending order. */ /* * Now sort the strings in descending order. */ qsort(strs, NSTRS, STRLEN, compare2); qsort(strs, NSTRS, STRLEN, compare2);

Page 19: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

qsortqsortprintf("\nSorted in descending order:\n"); printf("\nSorted in descending order:\n"); for (i = 0; i < NSTRS; i++) for (i = 0; i < NSTRS; i++)

printf("\t%s\n", strs[i]); printf("\t%s\n", strs[i]); exit(0); exit(0);

}//end main}//end main /* * compare1--compare a and b, and return less than/* * compare1--compare a and b, and return less than

greater than, or equal to zero. Since greater than, or equal to zero. Since we are comparing character strings, we we are comparing character strings, we can just use strcmp to do the work for us. */can just use strcmp to do the work for us. */

compare1(a, b) compare1(a, b) char *a, *b; { char *a, *b; { return(strcmp(a, b));return(strcmp(a, b)); } }

/* * compare2--this compares a and b, but is used for/* * compare2--this compares a and b, but is used for * sorting in the opposite order. Thus it * sorting in the opposite order. Thus it returns the opposite of strcmp. We canreturns the opposite of strcmp. We can* simulate this by simply reversing the* simulate this by simply reversing the* arguments when we call strcmp. */ * arguments when we call strcmp. */

compare2(a, b) compare2(a, b) char *a, *b; char *a, *b; {{ return(strcmp(b, a));return(strcmp(b, a)); } }

Page 20: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Function Pointers and Ordinary Function Pointers and Ordinary PointersPointers

C makes a clear distinction between the two types of C makes a clear distinction between the two types of pointerspointers

A data pointer only hold the address of the first byte of a A data pointer only hold the address of the first byte of a variablevariable

While function pointers share many similarities with While function pointers share many similarities with ordinary data pointers, they differ in several ways. First, ordinary data pointers, they differ in several ways. First, you can't declare a generic pointer to function similar to you can't declare a generic pointer to function similar to void*. In addition, trying to store a function pointer in a void*. In addition, trying to store a function pointer in a void* isn't guaranteed to work (certain compilers tolerate void* isn't guaranteed to work (certain compilers tolerate this, others don't). Finally, you can't dereference a this, others don't). Finally, you can't dereference a function pointer -- there's no such thing as passing a function pointer -- there's no such thing as passing a function by value.function by value.

Page 21: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

ReferencesReferences

““The C Programming Language”, Brian The C Programming Language”, Brian W.Kernighan, Dennis M.RitchieW.Kernighan, Dennis M.Ritchie

http://www.codetoad.com/c_pointers.asphttp://www.codetoad.com/c_pointers.asp http://www.eskimo.com/~scs/cclass/int/sx1http://www.eskimo.com/~scs/cclass/int/sx1

0.html0.html

Page 22: Pointers to Functions In C programming language. Introduction  While many programming languages support the concept of pointers to data, only a few enable

Thaaaaaaaaaaaaaanks!Thaaaaaaaaaaaaaanks!