Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building blocks of C programs Functions must be declared above their use in a source file, or enter a prototype. Example: float foo(int n, char s) { Instructions } Return type to left of name –float is the return type –Enter: void if none –If non-void, return needed (JLJ) Example: return 3.2; Argument list within () –argument name, type, order –formal arguments (parameters) –Passed by value A call –int m=5;foo(m, 'a'); –m and 'a' are actual arguments Prototype: float foo(int, char);
Direct and Indirect Addresses Pointers: memory address pointing the data –Java: All objects are pointers Java hides pointers from the programmer –C Objects may or may not be pointers The programmer has control but must be very careful Defining pointers –Direct addressing (JLJ): int n; n = 10; –Indirect addressing: int *np; *np = 10; n np
Example Swapping values Does Nothing – Why? Function void swap(int x,int y) { int temp = x; x = y; y = temp; } Call to swap function int a=5, b = 10; swap(a, b); This one works Function swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } Call to swap function int a=5, b = 10; swap(&a, &b); Note: Use direct addressing if not changing a parameter value Note: Use indirect addressing if changing a parameter value
Passing Pointers Nested function pass a pointer to a nested function Example: void foo1(int *a) { *a = 5; } void foo2(int *n) { foo1(n); } void main(int argc, char *argv[]) { int m=3; foo2(&m); printf("m = %d", m); } Notes –&m means address of m (convert direct to indirect addressing) –foo2 does not change n, so simply passes the pointer to foo1 –foo1 stores through the pointer indirectly –the printf statement prints a 5
Variable number of arguments #include double average ( int num,... ) // The … must be last { double sum = 0; int x; va_list args; va_start ( args, num ); for ( x = 0; x < num; x++ ) sum += va_arg( args, double ); va_end ( arguments ); return sum/num; } Example calls: printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) ); printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );
Pass a function to a function Quick sort function prototype from the C library void qsort(void *base, size_t nmemb, size_t size, int(*compare)(const void *, const void *)); Example function for comparing elements #include int int_sorter( const void *first, const void *second ) { return (*(int*)first – *(int*)second); } Sample Call: qsort( array, 10, sizeof( int ), int_sorter );
Inputting from stdin (standard input) Use the scanf function int scanf(template, arg1, arg2, … ) Description –The template string is like that of printf –Reads possibly multiple values –Returns the number of successful reads –The arguments are addresses of variables –Example: int n; scanf("%d", &n); Note: "bob" entered is invalid and scanf returns zero –Example: scanf("%d %d", &i, &j); Note: scanf ignores whitespace. Non-whitespace characters in the template string must match exactly
Input Example (float) # include int main(int argc, char *argv[]) {float v; printf("Enter a value: "); while (scanf("%f", &v) != 1) { printf("Error, try again: "); scanf(“%*s");} Notes 1.scanf(%*s) rereads and discards erroneous data 2.The while loop tries until we have one successful read 3.Note the %f in the template for inputting a float value
Function Prototypes Normally you type the function above its use in a source file Sometimes prototypes can be useful –They can be declared below main –External source files can refer to them –Why? Because large it is reasonable in large projects Prototype: return foo(arg types) gcc can compile and link separately –Compile: gcc –c file creates file.o –Link: gcc main file.o function.o –o main
Header Files Contain information for multiple source files To access a header file: #include "header.h" /* in same folder */ #include /* in $INCLUDE folders */ Header files contain –Function prototypes –#define statements –Other preprocessor directives Common header files used by C programs –stdio.h (for stream I/O) –stdlib.h (for C run time library functions)
Exiting a Program Use the exit function –Need stdlib.h –Some implementations includes it in stdio.h Example: if (value<0) exit(1); elseexit(0); Note: exit(0) is a good return, exit(≠0) indicates an error. In UNIX, the value is returned to the shell so it can output an appropriate error message.