CSC195, Class 24: Functions and Pointers Overview: * Detour: #include and #define directives. * Functions that return pointers. * Pointers to functions. + Contrast to Scheme. + Contrast to Java. * Lab. Notes: * An outline for the impromptu lecture is now available. * Homework 5 ready. * Questions about the postconditions of permute? + Look at it again (on the EBoard, 22) + Bring questions on Monday. * Why doesn't C see future function declarations? + If you call a function above where you declare it, C may complain about inconsistencies. main() { foo(bar); ... } void foo(int whatever) C compiler: Warning: "Attempt to redeclare foo. Who taught you to program?" The C compiler does (more-or-less) one pass through the code. The Java compiler does more than one. * Uses less memory. * Uses much less processor time. * Uses much less disk I/O. ---------------------------------------- The C preprocessor does an initial pass quick pass through the code to handle some very simple things quickly. #include filename * Shoves the contents of filename into your file exactly where the #include was. + May also include some notes to help C remember what went where. * Can include declarations * Can include code #define NAME expression * Uses the text of expression wherever NAME appears in the program. #define NAME(V1,V2,V3) expression A macro Wherever NAME(exp1,exp2,exp3) appears replaces V1 by exp1 in expression replaces V2 by exp2 in expression replaces V3 by exp3 in expression replace NAME(...) by modified expression #define SUM(x1,x2) { x1+x2 } printf("Sum: %d\n", SUM(34,5)): #define SQUARE(x) (x*x) printf("Val: %d", SQUARE(3+4)); printf("Val: %d", (3+4*3+4)); printf("Val: %d", SQUARE(++x)); #ifdef NAME arbitrary code #endif If you've defined NAME (earlier or on the command line), includes "arbitrary code". Otherwise, doesn't. #ifdef DEBUGGING #define WARNING(str) printf("%s",str) #else #define WARNING(str) #endif Play with some of this in lab. ---------------------------------------- Functions can return pointers. int *allocate_an_integer(void) { return (int *) malloc(sizeof(int)); } /* allocate_an_integer(void) */ ---------------------------------------- You can make pointers to functions * C doesn't let you pass functions around. * If you have cases in which you'd like to pass fucntions around, you gotta pass around pointers to functions. * E.g., the lessThan operation in a generalized binary search algorith (or equals in sequential search) How do you write "compare is a pointer to a function of two parameters, both of which are integers and returns an integer?" int search(int (*compare)(int x,int y) ...) (*compare)(2,3) ---------------------------------------- int slt(char *str1, char *str2) { while ((*str1) && (*str1++ == *str2++)) ; return *--str1 < *--str2; } /* slt(char*,char*) */