1 / 35

Functions

Functions. C standard library Function prototype, call, & definition Pass by value, reference Multiple-Source-File Programs Storage Classes Scope Recursion. C Standard Library. Prepackaged functions already written D & D textbook, Section 5.6, p. 154

fifi
Download Presentation

Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions • C standard library • Function prototype, call, & definition • Pass by value, reference • Multiple-Source-File Programs • Storage Classes • Scope • Recursion

  2. C Standard Library • Prepackaged functions already written • D & D textbook, Section 5.6, p. 154 • On web: http://www.infosys.utas.edu.au/info/documentation/C/CStdLib.html

  3. <assert.h> : Diagnostics • <ctype.h> : Character Class Tests • <errno.h> : Error Codes Reported by Library Functions • <float.h> : Implementation-defined Floating-Point Limits • <limits.h> : Implementation-defined Limits • <locale.h> : Locale-specific Information • <math.h> : Mathematical Functions • <setjmp.h> : Non-local Jumps • <signal.h> : Signals • <stdarg.h> : Variable Argument Lists • <stddef.h> : Definitions of General Use • <stdio.h> : Input and Output • <stdlib.h> : Utility functions • <string.h> : String functions • <time.h> : Time and Date functions

  4. Math Library Functions • Used for common mathematical calculations • Most arguments are of type double • All functions return a double • sqrt(x) – returns square root • exp(x) - ex • log(x) – ln x, logex • log10(x) – log10 x • fabs(x) – absolute value of x • pow(x,y) – x to the power of y

  5. Math Library Functions #include <stdio.h> #include <math.h> int main(void) { printf( "%f\n",log10( 100.0 ) ); return 0; } Output: 2.0 See math.c (note that the math library functions are not supported on the UHUNIX gcc software at this time)

  6. Random Number Generation • Use function rand() from the <stdlib.h> library • n = a + rand() % b; • n = pseudorandom number • a = shifting value (the 1st number in the range of integers) • b = scaling factor (the width of the range of integers) • srand(time (NULL)); • srand( ) = seeds the pseudorandom numbers • time ( ) = gives the current time in seconds (from <time.h>) • See Section 5.9

  7. Dice-Rolling Example • Simulates rolling a six-sided die 6000 times to test the random number generator • See rand.c

  8. Functions #include <stdio.h> int add3(int, int, int); int main(void) { printf("1+2+3=%d\n", add3(1,2,3)); return 0; } int add3(int a, int b, int c){ return a+b+c; }

  9. Functions int add3(int, int, int); • Function prototype • Compiler uses to validate function calls printf("%d\n", add3(1,2,3)); • Function call • Arguments int add3(int a, int b, int c){…} • Function definition • Return type, parameter types & names, body

  10. Possible Bugs • If a return type or parameter is not listed, then the compiler will assume it is of type "int" • The return type and the argument types of the function prototype & the function definition must be the same

  11. Possible Bugs #include <stdio.h> /*See bugs.txt*/ add3(int, int, int); int main(void) { add3(1,2,3); return 0; } void add3(int a, int b, int c){ printf("1+2+3=%d\n", a+b+c);} bugs.c:3: warning: data definition has no type or storage class bugs.c:11: error: conflicting types for `add3' bugs.c:3: error: previous declaration of `add3'

  12. Function Calls • Call by value • Copy of argument’s value is passed to function • Changes in the copy do not affect the original variable (no “side effects”) • All calls are calls by value in C • Call by reference • Can modify the argument’s value • Simulated in C by using pointers • Make a copy of address & modify the contents • Used in C arrays & pointers

  13. Class Exercise 1 #include <stdio.h> /*See exercise1.txt*/ int fun1(int, int); int main(void) { int x=10, y=20; printf("x=%d y=%d\n", x, y); y = fun1(x,y); printf("x=%d y=%d\n", x, y); return 0; } int fun1(int y, int x){ x++; y++; printf("x=%d y=%d\n", x, y); return x; }

  14. Main.c #include "hello.h" int main(){ funH(); return 0; } • Hello.h void funH(void); • Hello.c #include <stdio.h> #include "hello.h" void funH(void){ printf("Hello,\n"); } Multiple Files • File.c #include <stdio.h> void funH(void); int main(){ funH(); return 0; } void funH(void){ printf("Hello\n"); }

  15. Multiple File Makefile • Consist of sets of three lines • Target: list of dependencies • <tab>Commands needed to build target • Blank line • Example makefile: main: main.o hello.o gcc main.o hello.o -o main main.o: main.c hello.h gcc -c main.c hello.o: hello.c hello.h gcc -c hello.c

  16. Header File (filename.h) • Contains declarations & definitions common to separate program files (takes up no memory) • Macro definitions • Structure, union & enumeration declarations • Typedef declarations • Function declarations (function prototype) • Global variable declarations (uninitialized variables) • What you should not put in header files • Function definitions (function body) • Global variable definitions (initialized variables)

  17. Definition & Declaration • Definition • Refers to the place where the variable is created or assigned storage • Declaration • Refers to places where the nature of the variable is stated but no storage is allocated

  18. Storage Classes • C has four: auto, register, extern, static • A variable’s storage class determines its storage duration, scope, and linkage • Storage duration (automatic & static) • Period it exists in memory • Scope (file, function & block) • Where it can be referenced in a program • Linkage (internal & external) • Whether a variable is accessed only in current source file or in other source files

  19. Auto Storage Class • auto • Has automatic storage duration • Variable created when block is entered, exist while block is active, destroyed when block is exited • Default for all variables inside functions auto int x = 100;

  20. Register Storage Class • register • Also has automatic storage • Put variable in high-speed register • Compiler is free to ignore it register int counter = 1;

  21. Extern Storage Class • extern • Has static storage duration • Exists from start of program • Default for global variables & functions • Referenced by any function that follows its declaration • If a variable is used in a different file, then it must be declared “extern”, while the original variable must not be declared “extern”

  22. file2.c #include <stdio.h> extern int x; int main2(){ printf("x=%d\n",x); return 0; } file1.c #include <stdio.h> int x=50; int main(){ printf("x=%d\n",x); main2(); return 0; } gcc file1.c file2.c ./a.out x=50 x=50 Note: If you put global variables in a header file, then you don’t use the “extern” declaration

  23. Static Storage Class • static • Also has static storage duration • In functions • Declared in a function & retains its value when function is exited • Next time function is called, it still has the same value • As a global variable or function • Will be invisible outside the file (internal linkage)

  24. #include <stdio.h> /*See static.c.txt*/ int fun(void); int main(void) { printf("fun()=%d\n",fun()); printf("fun()=%d\n",fun()); printf("fun()=%d\n",fun()); return 0; } int fun(void){ static x = 10; x++; return x; } fun()=11 fun()=12 fun()=13

  25. file4.c #include <stdio.h> int x=10; int main2(){ printf("x=%d\n",x); return 0; } file3.c #include <stdio.h> static int x=50; int main(){ printf("x=%d\n",x); main2(); return 0; } gcc file3.c file4.c ./a.out x=50 x=10

  26. Scope • Portion of a program where a variable or function can be referenced • Four kinds • Function • File • Block • Function-prototype

  27. Function Scope • Can be used anywhere within a function • Only labels have function scope • Identifier followed by a colon • Used in switch & goto statements switch(ch){ case 'A': case 'a': a++; break; . . .} start: printf("hello"); goto start;

  28. File & Function-Prototype • File scope • Identifiers declared outside any function • Known from declaration to end of file • Global variables, function definitions, function prototypes • Function-prototype scope (quite useless) • Variables declared in function prototypes are not visible outside function

  29. Block Scope • Identifiers declared within a block • Only visible inside the block • Variables declared inside a block may hide any identically named variables in outer blocks • Will remain in existence until the matching right brace

  30. #include <stdio.h> /*See block.c.txt*/ int main(void){ int x = 10; { int x = 20; { int x = 30; printf("x=%d\n",x); } printf("x=%d\n",x); } printf("x=%d\n",x); return 0; } x=30 x=20 x=10

  31. Class Exercise 2 • See exercise2.txt

  32. Recursive Functions • When a function calls itself, each invocation gets a new set of variables, independent of the previous set • Consists of • Base case (stopping case) • Recursive case (simpler case) int fib(int x){ if(x <=1) return x; return fib(x-1) + fib(x-2); } /*See fib.txt*/

  33. Recursive Functions int factorial( int x ) { if(x == 0) return 1; return factorial(x - 1) * x; } /*See fact.c*/

  34. Recursion vs. Iteration • Negatives to recursion • Time & memory are used for function calls • Uses more time & memory, since each recursive call creates another copy of the function • Iteration has no such overhead • Positives to recursion • Can be easier to program & understand than iteration

  35. Class Exercise 3 • See exercise3.txt

More Related