Download presentation
Presentation is loading. Please wait.
Published byBarbra Harvey Modified over 8 years ago
1
Chapter 4 SlidesSlide 1 FUNCTIONS IN C – ELEMENTARY PROGRAM STRUCTURE
2
Chapter 4 SlidesSlide 2 We have already seen functions Functions that perform I/O operations –scanf( ), printf( ), getchar( ) Functions that use files –fopen(), fscanf, fprintf(), fclose
3
Chapter 4 SlidesSlide 3 We have already seen functions Functions that perform I/O operations –scanf( ), printf( ), getchar( ) Functions that use files –fopen(), fscanf, fprintf(), fclose And of course the one we have used most: –main()
4
Chapter 4 SlidesSlide 4 Simplest case: function has no arguments and no return value #include void print_message(void); int main(void) { int i; for (i = 0; i < 5; i++) print_message(); printf("\nI agree!\n"); } void print_message(void) { printf("Buy many copies\n"); }
5
Chapter 4 SlidesSlide 5 Simplest case: function has no arguments and no return value #include void print_message(void); The first void means no return value int main(void) { int i; for (i = 0; i < 5; i++) print_message(); printf("\nI agree!\n"); } void print_message(void) { printf("Buy many copies\n"); }
6
Chapter 4 SlidesSlide 6 Simplest case: function has no arguments and no return value #include void print_message(void); The first void means no return value. The second means no arguments. main has no arguments, either int main(void) { int i; for (i = 0; i < 5; i++) print_message(); printf("\nI agree!\n"); } void print_message(void) { printf("Buy many copies\n"); }
7
Chapter 4 SlidesSlide 7 Simplest case: function has no arguments and no return value #include void print_message(void);declaration of function, function prototype int main(void) { int i; for (i = 0; i < 5; i++) print_message(); printf("\nI agree!\n"); } void print_message(void) { printf("Buy many copies\n"); }
8
Chapter 4 SlidesSlide 8 Simplest case: function has no arguments and no return value #include void print_message(void);declaration of function, function prototype int main(void) { int i; for (i = 0; i < 5; i++) print_message();use of function printf("\nI agree!\n"); } void print_message(void) { printf("Buy many copies\n"); }
9
Chapter 4 SlidesSlide 9 Simplest case: function has no arguments and no return value #include void print_message(void);declaration of function, function prototype int main(void) { int i; for (i = 0; i < 5; i++) print_message();use of function printf("\nI agree!\n"); } void print_message(void)definition of function { printf("Buy many copies\n"); }
10
Chapter 4 SlidesSlide 10 Function prototypes Tell the compiler how much memory to allocate (usually in bytes) Tell the compiler how to interpret the contents –float –int –char –double, –etc
11
Chapter 4 SlidesSlide 11 We have seen this idea before Variables and constants must be declared before use This allows allocation of space and tells how the space is organized: int, float, char,...
12
Chapter 4 SlidesSlide 12 Functions have: A name List of arguments and their types go inside the parentheses (arguments are often called parameters) The return type goes outside, before the name This is often called the signature, also
13
Chapter 4 SlidesSlide 13 A function with a parameter and no return value #include void print_message(int i); /* prototype */ int main(void) { int i; for (i = 0; i < 5; i++) print_message(i);/* use */ printf("\nI agree!\n"); } void print_message(int i) /* definition */ { int j; for(j=0; j < i; j++) printf("Buy many copies\n"); }
14
Chapter 4 SlidesSlide 14 A function with a parameter: return value is never used #include int calculate(int); int main(void) { int i; for (i = 0; i < 5; i++) calculate(i); /* returned value is never used */ } int calculate(int i) { printf("The original number was %d\n",i); return (i+2); /* value is returned */ }
15
Chapter 4 SlidesSlide 15 A function with a parameter: return value is used #include int calculate(int); int main(void) { int i; for (i = 0; i < 5; i++) printf(”Calculated value is %d\n”, calculate(i)); /* uses returned value */ } int calculate(int i) { printf("The original number was %d\n",i); return (i+2); /* value is returned */ }
16
Chapter 4 SlidesSlide 16 A function with a parameter: return value is used #include int calculate(int); int main(void) {can nest function calls int i; for (i = 0; i < 5; i++) printf(”Calculated value is %d\n”, calculate(i)); /* uses returned value */ } int calculate(int i) { printf("The original number was %d\n",i); return (i+2); /* value is returned */ }
17
Chapter 4 SlidesSlide 17 A function with a parameter: return value is used #include int calculate(int); int main(void) {can nest function calls int i; for (i = 0; i < 5; i++) printf(”Calculated value is %d\n”, calculate(i)); /* uses returned value */ } int calculate(int i) { printf("The original number was %d\n",i); return (i+2); /* value is returned */ } Here, function main calls printf, function printf calls calculate, calculate does its job
18
Chapter 4 SlidesSlide 18 What’s happening here? FunctionEnviron- ment level ArgumentsLocal variables Callsreturns main()1noneiprintf()unknown printf()2”calculated value is %d\n”, calculate(i) unknown – printf is a library function calculate()unknown calculate () 3inonenothingi + 2
19
Chapter 4 SlidesSlide 19 What’s happening here? FunctionEnviron- ment level ArgumentsLocal variables Callsreturns main()1nonei (starts at 0) printf()unknown printf()2”calculated value is %d\n”, calculate(i) unknown – printf is a library function calculate()unknown calculate () 3i (still is 0)nonenothingi + 2 (0 + 2)
20
Chapter 4 SlidesSlide 20 What’s happening here? FunctionEnviron- ment level ArgumentsLocal variables Callsreturns main()1nonei (starts at 0) printf()unknown printf()2”calculated value is %d\n”, calculate(i) unknown – printf is a library function calculate()unknown calculate () 3i (still is 0)nonenothingi + 2 (0 + 2) Execution goes up as the functions return
21
Chapter 4 SlidesSlide 21 What’s happening here? FunctionEnviron- ment level ArgumentsLocal variables Callsreturns main()1nonei (starts at 0) printf()unknown printf()2”calculated value is %d\n”, 3 unknown – printf is a library function calculate()unknown calculate () 3i (still is 0)nonenothingi + 2 (0 + 2) Execution goes up as the functions return
22
Chapter 4 SlidesSlide 22 What’s happening here? FunctionEnviron- ment level ArgumentsLocal variables Callsreturns main()1nonei (incremen- ted to 1) printf()unknown printf()2”calculated value is %d\n”, 3 unknown – printf is a library function calculate()unknown calculate () 3i (still is 0)nonenothingi + 2 (0 + 2) Execution goes up as the functions return
23
Chapter 4 SlidesSlide 23 Execution continues The loop counter in main() goes to 5 and the second loop control condition (i<5) is false Five iterations of the loop The main program stops and control gets back to the operating system (environment level 0)
24
Chapter 4 SlidesSlide 24 Why is the environment level important? It provides a way to tell differences between variables of the same name. What happens in the previous program if we change the function calculate() to include a local variable and “overload” the name of this variable?
25
Chapter 4 SlidesSlide 25 Is there confusion? int calculate(int j) { int i;/* a local variable */ printf("The original number was %d\n",j); return (i = j+2); /* value is returned */ } /*The local variable, i, and the argument in the function call from main() have the same name. */
26
Chapter 4 SlidesSlide 26 How does the compiler keep these names straight? Its internal representation includes the environment level and the name and type of the variable. So, a variable named i in environment level 3 (calculate()) is not related to a variable named i in main(), which is environment level 1.
27
Chapter 4 SlidesSlide 27 How do you keep them straight? Your only problem is potential confusion between the name of an argument and a local variable of the same name. Ex: int calc2(int i) {int i, j; … a bad idea – can’t tell which one you mean } Just use different names for local variables and arguments.
28
Chapter 4 SlidesSlide 28 How does the compiler store functions? The code is stored with its data and instructions. Brief descriptions of functions are also available in their signatures: –Name –Return type –Argument list (each argument has a type, order matters)
29
Chapter 4 SlidesSlide 29 How does C handle function calls? There is a run-time system, which works in conjunction with the computer’s operating system. This run-time system is related to the “workspace” in Microsoft Visual Studio. One important part is the run-time stack, which keeps track of functions, arguments, and return values.
30
Chapter 4 SlidesSlide 30 Example of a run-time stack #include int main(void) { int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; }
31
Chapter 4 SlidesSlide 31 This code has many changes of environment When it begins execution in main(), environment level is 1. When it enters printf(), environment level is 2. When it exits printf(), environment level is 1. When it enters scanf(), environment level is 2. When it exits scanf(), environment level is 1. When it enters printf(), environment level is 2. When it exits printf(), environment level is 1. When it exits main(), environment level is 0 (operating system). Each environment is different.
32
Chapter 4 SlidesSlide 32 Here’s how the stack works Start execution in main(), no args #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: push data Env. Level is 1 Nameargvalue main()…
33
Chapter 4 SlidesSlide 33 Here’s how the stack works Call printf(), arg is a string #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: push data Env. Level is 2 Nameargvalue printf() “Please…” main()…
34
Chapter 4 SlidesSlide 34 Here’s how the stack works Exit printf() #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: pop data from stack Env. Level is 1 Nameargvalue main()…
35
Chapter 4 SlidesSlide 35 Here’s how the stack works Enter scanf() #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: push data onto stack Env. Level is 2 Nameargvalue scanf()“The…”, &i main()…
36
Chapter 4 SlidesSlide 36 Here’s how the stack works Exit scanf() #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: pop data from stack Env. Level is 1 Nameargvalue main()…
37
Chapter 4 SlidesSlide 37 Here’s how the stack works Enter printf() #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: push data onto stack Env. Level is 2 Nameargvalue printf()“The..”, i main()…
38
Chapter 4 SlidesSlide 38 Here’s how the stack works Exit printf() #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: pop data from stack Env. Level is 1 Nameargvalue main()…
39
Chapter 4 SlidesSlide 39 Here’s how the stack works Exit main() #include int main(void) {int i; printf("Please enter a positive integer\n"); scanf("%d", &i); printf("The integer is %d\n", i) ; } Stack: pop data from stack Env. Level is 0 Nameargvalue Operating system
40
Chapter 4 SlidesSlide 40 We are done (almost) We returned control to the operating system. There can be communication with the operating system (discussed later in Chapter 5).
41
Chapter 4 SlidesSlide 41 Storage Classes in C These are used to modify the type of a variable –Automatic: the default, everything we have done used these –Static (next few slides) –Extern (next few slides) –Register: uses super-fast memory registers – we won’t use these –Void: no variable type, used in function signatures
42
Chapter 4 SlidesSlide 42 Static variables A variable that is intended to be retained between successive function calls must be declared using the static qualifier. Without use of static, results are unpredictable.
43
Chapter 4 SlidesSlide 43 /* produces garbage sometimes */ #include void mystery(void); void not_a_mystery(void); int main(void) { mystery(); not_a_mystery(); mystery(); not_a_mystery(); }
44
Chapter 4 SlidesSlide 44 What is the value of i? /* use of uninitialized automatic variable - can cause unpredictable results */ void mystery(void) { int i; i = i + 1; printf("in mystery, i is %d\n",i); }
45
Chapter 4 SlidesSlide 45 The value of temp is clearer /* correct use of local static variable */ void not_a_mystery(void) { static int temp; temp++; printf("in not_a_mystery, temp is %d\n",temp); }
46
Chapter 4 SlidesSlide 46 Another difference between static and automatic Static variables are always guaranteed to be initialized to 0. Automatic variables are not guaranteed to be initialized and can have any values. Don’t count on variables being initialized – do the initialization yourself.
47
Chapter 4 SlidesSlide 47 Extern variables Variables that are used, but not defined, within any function are called external variables and are declared using the qualifier extern. Example of their use: the swapping program using the variables to be swapped as global variables. If these external variables are given at the beginning of a C source code file, they can be used by any functions in that file.
48
Chapter 4 SlidesSlide 48 Extern variables As with static variables, they are guaranteed to be given the initial value of 0 if they are not explicitly initialized by the programmer. Probably better to initialize them anyway, for clarity.
49
Chapter 4 SlidesSlide 49 Scope: what’s the value of i? void f(int);int i, j; int main(void) { int i, j; i = 4 ; j = 2; f(j); } void f(int x) { int i, j; i = 3; j = 1; i = j; }
50
Chapter 4 SlidesSlide 50 Scope: what’s the value of i? void f(int);int i, j; globals int main(void) { int i, j; i = 4 ; i is 4 j = 2;j is 2 f(j); } void f(int x) { int i, j; i = 3;the same i is now 3 j = 1;the same j is now 1 i = j; }i is now 1
51
Chapter 4 SlidesSlide 51 Scope Rules for Functions in a Single Source File 1. If the variable is defined inside a function, then its scope is that function. Static variables retain their values on successive function calls while automatic variables do not. Neither is available outside the defining function. 2. If the variable is defined outside every function, then it will be available to any function defined from that point to the end of the file. 3. If the variable is defined outside every function, then it can be made available to any function in the file by declaring the variable to be extern in the function that wishes to use it. In this case the variable is global. 4. The C language does not permit a function to be defined inside another function.
52
Chapter 4 SlidesSlide 52 A C construct I do not like It is possible for variables to have a nested scope in C. f() {int i = 1 ; { int i; i = 2;... }... }
53
Chapter 4 SlidesSlide 53 A C construct I do not like It is possible for variables to have a nested scope in C. f() {int i = 1 ; { int i; This one hides the enclosing one i = 2;... }... }
54
Chapter 4 SlidesSlide 54 Functions often return values If the function is not intended to return a value, then no return statement should be included in the body of the function. Otherwise, each function execution path must return a value.
55
Chapter 4 SlidesSlide 55 Function declarations 1. Decide what the type of each function should be. 2. Provide a function prototype for each function. 3. To prevent accidentally using the value returned by a function when no result is intended, use the qualifier "void" in the declaration. 4.If a function is to be defined elsewhere, use the extern declaration extern fcn_type fcn_name(arg_type arguments, etc )
56
Chapter 4 SlidesSlide 56 Some compiler warning messages main() returns random value to invocation environment printf function returns value which is always ignored average function returns value which is sometimes ignored
57
Chapter 4 SlidesSlide 57 Some compiler warning messages main() returns random value to invocation environmentOK for now printf function returns value which is always ignoredOK – this is the number of bytes printed average function returns value which is sometimes ignoredprobably not OK – what did you mean?
58
Chapter 4 SlidesSlide 58 The C preprocessor The role of a preprocessor is to set values that are to be used in a C program. A pre-processor also transforms certain code into assembly language instructions that are included in the code as needed. Finally, the preprocessor arranges for appropriate files to be included in the program.
59
Chapter 4 SlidesSlide 59 Some examples #include #define MAX 10 #define MSG "Hello“ #ifndef INT_MAX #define INT_MAX 32767
60
Chapter 4 SlidesSlide 60 #define min(x,y) ((x) > (y) ? (y): (x) ) /* if the value of x is greater than y, then y, else x */ Same effect as min(int x, int y) { if ( x > y ) return y; else return x; }
61
Chapter 4 SlidesSlide 61 Library functions /* corrected version of example 4.20 */ #include int main(void) { double x = 4.0; printf("%lf\n", sqrt(x)); }
62
Chapter 4 SlidesSlide 62 The math library Standardized minimum number of functions Included using #include Need to match the signature of each function called (this was the error in example 4.20 – which was never intended to compile – types should be double).
63
Chapter 4 SlidesSlide 63 Differences in program environments In Microsoft Visual Studio, just compiling is sufficient, since the linking is automatic. In many other environments, an additional linking step is necessary. –On some systems running the GNU gcc compiler (the basis for the Xcodes on Macintoshes), link the math library, lm, by gcc ex4.20.c -lm
64
Chapter 4 SlidesSlide 64 Standard C libraries assert.h : used with preprocessor for debugging purposes ctype.h : character handling errno.h : error-handling macros float.h : floating point constants limits.h : integer limits locale.h : local standards (countries) math.h : standard math functions setjmp.h : nonlocal jumps for nonlocal GOTO
65
Chapter 4 SlidesSlide 65 Standard C libraries, cont. signal.h : signals, event detection stddef.h : commonly used constants, international character sets (Unicode) stdio.h : I/O functions stdlib.h : functions for general use stdarg.h : writing functions with variable numbers of arguments string.h : string handling time.h : system clock access
66
Chapter 4 SlidesSlide 66 Only a few of these standard libraries will be used in this course Many others are more appropriate for operating system-level programming.
67
Chapter 4 SlidesSlide 67 Review of function calls C functions can easily call other C functions. When a function is called, copies made of each argument are made and execution begins in the function. The called function continues execution until either a return statement is reached or the function is exited because no more statements are to be executed. The compiler places copies of parameters are placed on a stack and they are popped off the stack, last-in–first-out, when they are used. Think of a stack of trays in a cafeteria.
68
Chapter 4 SlidesSlide 68 #include #define PI_OVER_2 1.5708 void print_trig_table(double); int main(void) {double increment; printf("This program will print a table of the sine and cosine functions\n"); printf("The calculations will be displayed to 4 decimal places.\n"); printf("Please enter the increment for the table in the range 0..1\n\n"); scanf("%lf", &increment); print_trig_table(increment); }
69
Chapter 4 SlidesSlide 69 #include #define PI_OVER_2 1.5708 void print_trig_table(double); int main(void) {double increment; printf("This program will print a table of the sine and cosine functions\n"); printf("The calculations will be displayed to 4 decimal places.\n"); printf("Please enter the increment for the table in the range 0..1\n\n"); scanf("%lf", &increment); print_trig_table(increment); } Constant
70
Chapter 4 SlidesSlide 70 /*comments about this function's purpose*/ void print_trig_table(double incr) { double x; for (x = 0.0; x <= PI_OVER_2; x += incr) printf("%5.4lf%6.4lf%6.4lf\n", x, sin(x), cos(x) ); }
71
Chapter 4 SlidesSlide 71 /*comments about this function's purpose*/ void print_trig_table(double incr) { double x; for (x = 0.0; x <= PI_OVER_2; x += incr) printf("%5.4lf%6.4lf%6.4lf\n", x, sin(x), cos(x) ); } Formatting NOTE: Tabs don’t display well on screen
72
Chapter 4 SlidesSlide 72 Can have multiple functions Perhaps even defined elsewhere: extern double my_rand (void);
73
Chapter 4 SlidesSlide 73 Another example double my_rand(int);/* A pseudo-random number generator */ int main(void) { int seed = 1999331;/* used for the pseudo-random number generator */ int i; /* Print the random number table - 10 table entries */ for (i = 0; i <=10; i++) printf("Random number is %lf\n", my_rand(seed) ); }
74
Chapter 4 SlidesSlide 74 double my_rand(int seed) /* returns pseudo-random number in [0, 1] */ { /* uses static variable, for consecutive function calls.*/ double rand; static int product = 23230109; product = abs ((seed * product) % 12393267 ); /* absolute value */ printf("product is %d\n", product);/* helps with debugging -remove from final */ /* coerce double precision arithmetic*/ /* The value of rand is between 0 and 1 */ rand = ( ( (double) product ) / 12393267); return rand; }
75
Chapter 4 SlidesSlide 75
76
Chapter 4 SlidesSlide 76 What’s happening here? A value inside the function is available in successive function calls Only possible with the use of the static storage class for variables
77
Chapter 4 SlidesSlide 77 double my_rand(int seed) /* returns pseudo-random number in [0, 1] */ { /* uses static variable, for consecutive function calls.*/ double rand; static int product = 23230109; product = abs ((seed * product) % 12393267 ); /* absolute value */ /* coerce double precision arithmetic*/ /* The value of rand is between 0 and 1 */ rand = ( ( (double) product ) / 12393267); return rand; } A new function
78
Chapter 4 SlidesSlide 78 double my_rand(int seed) /* returns pseudo-random number in [0, 1] */ { /* uses static variable, for consecutive function calls.*/ double rand; static int product = 23230109; product = abs ((seed * product) % 12393267 ); /* absolute value */ /* coerce double precision arithmetic*/ /* The value of rand is between 0 and 1 */ rand = ( ( (double) product ) / 12393267); return rand; } A new function Modulus operator: remainder
79
Chapter 4 SlidesSlide 79 double my_rand(int seed) /* returns pseudo-random number in [0, 1] */ { /* uses static variable, for consecutive function calls.*/ double rand; static int product = 23230109; product = abs ((seed * product) % 12393267 ); /* absolute value */ /* coerce double precision arithmetic*/ /* The value of rand is between 0 and 1 */ rand = ( ( (double) product ) / 12393267); return rand; } A new function Modulus operator: remainder Forces arithmetic to be double precision, not int
80
Chapter 4 SlidesSlide 80 There are disadvantages to this pseudo-random number generator Will gets the same sequence with each run of the program – not truly random enough Many random number generators look like this (with better choice of the prime numbers used in the calculation) Can get a more random seed
81
Chapter 4 SlidesSlide 81 Often the system clock time is used How? Choosing the seconds in the time Change to a seed format Functions in the include file time.h are used
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.