Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions in C and C++ CS-2303 System Programming Concepts Hugh C. Lauer (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.

Similar presentations


Presentation on theme: "Functions in C and C++ CS-2303 System Programming Concepts Hugh C. Lauer (Slides include materials from The C Programming Language, 2nd edition, by Kernighan."— Presentation transcript:

1 Functions in C and C++ CS-2303 System Programming Concepts Hugh C. Lauer (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5th and 6th editions, by Deitel and Deitel) CS-2303, A-Term 2012 Functions in C and C++

2 Definition – Function A fragment of code that accepts zero or more argument values, produces a result value, and has zero or more side effects. A means of encapsulating a subset of a program or a system To hide details To be invoked from multiple places To share with others A function in C is equivalent to a method in Java, but without the surrounding class CS-2303, A-Term 2012 Functions in C and C++ 2

3 Functions – a big Topic Examples Function definition
Function prototypes & Header files Pre- and post-conditions Scope rules and storage classes Implementation of functions Recursive functions CS-2303, A-Term 2012 Functions in C and C++ 3

4 Reading Assignment Chapter 4 of K&R CS-2303, A-Term 2012
Functions in C and C++

5 Common Functions in C #include <math.h> #include <stdio.h>
sin(x) // radians cos(x) // radians tan(x) // radians atan(x) atan2(y,x) /* atan(y/x), even when x == 0 */ exp(x) // ex log(x) // loge x log10(x) // log10 x sqrt(x) // x  0 pow(x, y) // xy ... #include <stdio.h> printf() fprintf() scanf() sscanf() ... #include <string.h> strcpy() strcat() strcmp() strlen() CS-2303, A-Term 2012 Functions in C and C++ 5

6 Common Functions (continued)
In K&R <assert.h> // for diagnostics, loop invariants, etc. <stdarg.h> // for parsing arguments <time.h> // time of day and elapsed time <limits.h> // implementation dependent numbers <float.h> // implementation dependent numbers <setjmp.h> // beyond scope of this course <signal.h> // beyond scope of this course CS-2303, A-Term 2012 Functions in C and C++ 6

7 Common Functions (continued)
See also the man pages of your system for things like <pthread.h> // concurrent execution <socket.h> // network communications ... // many, many other facilities Fundamental Rule: if there is a chance that someone else had same problem as you, … … there is probably a package of functions to solve it in C! CS-2303, A-Term 2012 Functions in C and C++ 7

8 Functions in C resultType functionName(type1 param1, type2 param2, …) { body } If no result, resultType should be void Warning if not! If no parameters, use void between () CS-2303, A-Term 2012 Functions in C and C++ 8

9 Functions in C resultType functionName(type1 param1, type2 param2, …) { body } //functionName If no result, resultType should be void Warning if not! If no parameters, use void between () It is good style to end a function with a comment showing its name CS-2303, A-Term 2012 Functions in C and C++ 9

10 N = f(pi*pow(r,2), b+c) + d;
Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used in any expression where a value of type int can be used – e.g., N = f(pi*pow(r,2), b+c) + d; CS-2303, A-Term 2012 Functions in C and C++

11 Definitions Parameter:– a declaration of an identifier within the '()' of a function declaration Used within the body of the function as a variable of that function Initialized by the caller to the value of the corresponding argument. Argument:– an expression passed when a function is called; becomes the initial value of the corresponding parameter Note: Changes to parameters within the function do not propagate back to caller! All parameters “call by value,” — as in Java CS-2303, A-Term 2012 Functions in C and C++

12 N = f(pi*pow(r,2), b+c) + d;
Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used in any expression where a value of type int can be used – e.g., N = f(pi*pow(r,2), b+c) + d; These are parameters These are arguments CS-2303, A-Term 2012 Functions in C and C++

13 Parameters and Arguments
Parameters are variables (or constants) that can be used inside of functions Arguments are expressions that are evaluated at call time and use to initialize parameters CS-2303, A-Term 2012 Functions in C and C++

14 Note Functions in C do not allow other functions to be declared within them Like C++, Java Unlike Algol, Pascal All functions defined at “top level” of C programs (Usually) visible to linker Can be linked by any other program that knows the function prototype Can “see” anything declared previously in same program (or in an included interface) CS-2303, A-Term 2012 Functions in C and C++

15 Note on printf parameters
int printf(char *s, ...) { body } // printf In this function header, “…” is not a professor’s shorthand (as often used in these slides) …but an actual sequence of three dots (no spaces between) Meaning:– the number and types of arguments is indeterminate Use <stdarg.h> to extract the arguments Also scanf(char *s, …); CS-2303, A-Term 2012 Functions in C and C++ 15

16 Questions? CS-2303, A-Term 2012 Functions in C and C++ 16

17 Function Prototypes There are many, many situations in which a function must be used separate from where it is defined – before its definition in the same C program In one or more completely separate C programs This is actually the normal case! Therefore, we need some way to declare a function separate from defining its body. Called a Function Prototype CS-2303, A-Term 2012 Functions in C and C++ 17

18 Function Prototypes (continued)
Definition:– a Function Prototype in C is a language construct of the form:– return-type function-name (parameter declarations) ; I.e., exactly like a function definition, except with a ';' instead of a body in curly brackets Essentially, the method of a Java interface. aka function header CS-2303, A-Term 2012 Functions in C and C++ 18

19 Purposes of Function Prototype
So compiler knows how to compile calls to that function, i.e., number and types of arguments type of result … without knowing anything about how it is defined! As part of a “contract” between developer and programmer who uses the function As part of hiding details of how it works and exposing what it does. A function header serves as a “black box.” CS-2303, A-Term 2012 Functions in C and C++ 19

20 Questions? CS-2303, A-Term 2012 Functions in C and C++

21 “Contract” between Developer and User of a Function
Function Prototype The pre- and post-conditions I.e., assertions about what is true before the function is called and what is true after it returns. A logical way of explaining what the function does CS-2303, A-Term 2012 Functions in C and C++ 21

22 Definitions Pre-condition:–a characterization or logical statement about the values of the parameters, and values of relevant variables outside the function prior to calling the function Post-condition:–a logical statement or characterization about the result of the function in relation to the values of the parameters and pre-conditions, and changes to values of variables outside the function after the function returns CS-2303, A-Term 2012 Functions in C and C++ 22

23 Example 1 double sin (double angle);
Pre:– angle is expressed in radians Post:– result is the familiar sine of angle Note: this function does not use or change any other variables CS-2303, A-Term 2012 Functions in C and C++ 23

24 Example 2 int printf (string, arg1, arg2, …)
Pre:– string is terminated with '\0' and contains conversion specifiers Pre:– a buffer maintained by the file system contains zero or more unprinted characters from previous calls. Post:– args are substituted for conversion codes in copy of string; resulting string is added to buffer Post:– if '\n' is anywhere in buffer, line is “printed” up to '\n'; printed characters are cleared from buffer Post:– result is number of characters added to buffer by printf CS-2303, A-Term 2012 Functions in C and C++ 24

25 Example 3 float total = 0; int count = 0; int GetItem(void) { float input; int rc; printf("Enter next item:- "); if ((rc = scanf("%f", &input)) != EOF && (rc > 0)) { total += input; count++; }; // if return rc; } // GetNewItem CS-2303, A-Term 2012 Functions in C and C++ 25

26 Example 3 Pre:– total is sum of all previous inputs, or zero if none Pre:– count is number of previous inputs, or zero if none Post:– if valid input is received total = totalprev + input, count = countprev + 1 float total = 0; int count = 0; int GetItem(void) { float input; int rc; printf("Enter next item:- "); if ((rc = scanf("%f", &input)) != EOF && (rc > 0)) { total += input; count++; }; // if return rc; } // GetNewItem CS-2303, A-Term 2012 Functions in C and C++ 26

27 Important Pre- and post-conditions are analogous to loop invariants
I.e., they describe something about the data before and after a function is called and the relationship that the function preserves Often are used together with loop invariants … to show that loop invariant is preserved from one iteration to the next CS-2303, A-Term 2012 Functions in C and C++ 27

28 Questions? Next Topic CS-2303, A-Term 2012 Functions in C and C++ 28


Download ppt "Functions in C and C++ CS-2303 System Programming Concepts Hugh C. Lauer (Slides include materials from The C Programming Language, 2nd edition, by Kernighan."

Similar presentations


Ads by Google