320 likes | 470 Views
Chapter 4. Functions and Program Structure. Introduction. Functions break large computing tasks into smaller ones Appropriate functions hide details of operation from parts of the program that don’t need to know about them Thus clarifying the whole
E N D
Chapter 4 Functions and Program Structure
Introduction Functions break large computing tasks into smaller ones Appropriate functions hidedetails of operation from parts of the program that don’t need to know about them Thus clarifying the whole And easing the pain of makingchanges C has been designed to make functions efficient and easy to use C programs generally consist of many small functions rather than a few big ones A program may reside in one or more source files
Basics of Function return-type function-name (argument declarations) { declarations and statements } Various parts may be absent A minimal function is: dummy( ) { } Which does nothing and returns nothing Sometimes useful as a place holder during program development Functions declaration must be used
Basics of Function Contd. A program is just a set of definitions of variables and functions Communication between the functions is by Arguments Values returned by the functions, and Through external variables The functions can occur in any order in the source file
Basics of Function Contd. The source program can be split into multiple files The return statement is the mechanism for returning a value from the called function to its caller return expression;
Basics of Function Contd. The calling function is free to ignore the returned value There need be no expression after return In that case, no value is returned to the caller Control also returns to the caller with no value when execution "falls off the end", i.e., “}”
External Variable External variables are globally accessible They provide an alternative to function arguments and return values for communicating between functions If a large number of variables must be shared among functions, external variables are more convenient and efficient than long argument list
External Variable Contd. However, this reasoning should be applied with some caution External variables are also useful because of their greater scope and lifetime Internal variables come into existence when the function is ended If two functions must share some data, yet neither calls the other, it is often most convenient to use external variables rather than passed in and out via arguments
External Variable: Where needed? #define MAXVAL 100 int sp = 0; double val [MAXVAL]; void push (double f){ if (sp < MAXVAL) val [sp++] = f; else printf (“Overflow”); } double pop (){ if (sp > 0) return val [--sp]; else { printf (“Under flow”); return 0.0; } }
Scope Rules • The source text of the program may be kept in several files • The concerns are • Variable declaration • Properly declared • Only one copy • Initialization • The scope of a name is that part of the program within which the name can be used
Scope Rules Contd. • For local variables • For external variables or a function (from that point) • If an external variable is to be referred to • before it is defined, or • if it is used in different source file from where it is used • then externdeclaration ismandatory • No storage allocation
Extern Declaration • There must be only one definition of an external variable among all the files • There may also be extern declaration in the file containing definition • Array size must be specified with the definition but are optional with an extern declaration • Initialization of an external variable goes only with definition
Header Files • If certain functions will be pretty common and be useful to many programs a head • Then those functions can be kept in a header file (extension is .h) and put in the library directory • Think about the necessity of the functions defined in stdio.h
Static Variables • Unlike automatic variables static variables remain in existence between functions calls • Static variables provide private, permanentstorage within a single function • The static variable is initialized only the first time the block is entered static int i = 0;
Register Variables register int x; • A register declaration advises the compiler that the variable will be heavily used • Register variables are to be placed in machine registers • Result in faster programs • The index of the innermost loop can be register variable • It is not possible to take the address of a register variable • It specific restrictions on number and types of register variables vary from machine to machine
Block Structure • Variables can be declared in any block “{}” • Variables declared in this way hide any identicallynamed variables in outer block • An automatic variable declared and initialized in a block is initialized each time the block is entered • The static variable is initialized only the first time the block is entered • Automatic variables, including formalparameters also hideexternalvariables and functions of the same name
Initialization • Automatic and register variables • External and static variables • Initializing arrays
Recursive Function • A function may call itself • When a function call itself recursively, each invocation gets a fresh set of all the automatic variables • Recursion may provide no saving in storage nor will be faster • Because of stack entry • But recursive code is more compact and often much easier to write • Recursion is especially convenient for recursively defined data structures (tree)
Criteria of Recursive Function • A terminating condition • Recursive definition
Factorial has a recursive definiton int factr(int n){ if(n == 0) return 1; //terminating condition else //recursive definition return n*factr(n-1); } int facti(int n){ int i, product = 1; for(i = 2; i <= n; i++) product *= i; return product; }
Itoa void itoa(int n, char s[]){ static int i; if(n/10){ itoa(n/10,s); //recursive definition s[i++] = n % 10 + '0'; s[i + 1] = 0; } else{ s[i++] = n % 10 + '0'; //terminating return; } } void itoa (int n, char s[ ]){ if ((sign = n) < 0) n = -n; /* make it positive */ i = 0; do{ s [i++] = n % 10; + ‘0’; } while ((n /= 10) > 0); if (sign < 0) s [i++] = ‘-’; s [i] = ‘\0’; reverse (s); }
int bsearch(int x, int v[], int low, int high){ static mid; if(low > high) return -1; mid = (low + high)/2; if(x < v[mid]) return bsearch(x, v,low,mid-1); else if(x > v[mid]) return bsearch(x, v, mid + 1, high); else return mid; } int binsearch(int x, int v[ ], int n){ int low, high, mid; low = 0; high = n -1; while(low <= high){ mid = (low + high)/2; if (x < v[mid]) high = mid – 1; else if(x > v[mid]) low = mid + 1; else return mid; } return -1; }
The C Preprocessor • The first step in compilation • File inclusion • Macro substitution • Conditional inclusion
File Inclusion • #include “filename” • #include <filename>
Macro Substitution • #define name replacement text • Normally the replacement text is the rest of the line • A long definition can be continued to several lines by placing a \ • Array declaration #define ARRAYLIMIT 20 char str[ARRAYLIMIT];
Macro Substitution Contd. #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) x = MAX(p+q, r+s); • There is no need to define different MAX for different data types
Macro Substitution Contd. #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) x = MAX(p+q, r+s); • There is no need to define different MAX for different data types
Macro Substitution Contd. #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) x = MAX(p+q, r+s); • There is no need to define different MAX for different data types
Macro Substitution Contd. MAX(i++, j++); //wrong #undef getchar int getchar(){ }
Macro Substitution Contd. • # in the replacement text #define DPRINT(EXP) printf(#EXP “ = %g\n”, EXP) DPRINT(x/y); is expanded printf(“x/y” “ = %g\n”, x/y); The two strings are concatenated like printf(“x/y = %g\n”, x/y);
Macro Substitution Contd. • The ## provides a way to concatenate actual arguments during macro expansion • #define CON(FRONT, BACK) FRONT##BACK • CON(12, 34)
Conditional Inclusion #if !defined(HDR) #define HDR …..\ …. #endif