Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.

Similar presentations


Presentation on theme: "Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize."— Presentation transcript:

1 Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize them into subprograms. These subprograms are called functions. They can be compiled and tested separately and reused in different programs. This modularization is characteristic of successful object-oriented software. The Standard C++ Library is a collection of pre-defined functions and other program elements which are accessed through header files. We have used some of these already: the sqrt() function defined in, the rand() function defined in, and the time() function defined in.

2 Some Functions Defined in the Header

3 Some of the Header Files in the Standard C++ Library

4 USER-DEFINED FUNCTIONS The great variety of functions provided by the Standard C++ Library is still not sufficient for most programming tasks. Programmers also need to be able to define their own functions. Here is a simple example of a user-defined function: int cube(int x) { // returns cube of x: return x*x*x; } The function returns the cube of the integer passed to it. Thus the call cube(2) would return 8. A user-defined function has two parts: its head and its body. The syntax for the head of a function is return-type name(parameter-list) The body of a function is the block of code that follows its head. It contains the code that performs the function’s action, including the return statement that specifies the value that the function sends back to the place where it was called.

5 TEST DRIVERS Whenever you create your own function, you should immediately test it with a simple program. Such a program is called a test driver for the function. Its only purpose is to test the function. It is a temporary, ad hoc program that should be “quick and dirty.” That means that you need not include all the usual niceties such as user prompts, output labels, and documentation. Once you have used it to test your function thoroughly you can discard it. int max(int x,int y) { // returns larger of the two given integers: if (x < y) return y; else return x; } int main() { // tests the max() function: int m,n; do { cin >> m >> n; cout << "\tmax(" << m << "," << n << ") = " << max(m,n) << endl; } while (m != 0); }

6 FUNCTION DECLARATIONS AND DEFINITIONS The last two examples illustrate one method of defining a function in a program: the complete definition of the function is listed above the main program. This is the simplest arrangement and is good for test drivers. Another, more common arrangement is to list only the function’s header above the main program, and then list the function’s complete definition (head and body) below the main program. In this arrangement, the function’s declaration is separated from its definition. A function declaration is simply the function’s head, followed by a semicolon. A function definition is the complete function: header and body. A function declaration is also called a function prototype. A function declaration is like a variable declaration; its purpose is simply to provide the compiler with all the information it needs to compile the rest of the file. The compiler does not need to know how the function works (its body). It only needs to know the function’s name, the number and types of its parameters, and its return type. This is precisely the information contained in the function’s head.

7 FUNCTION DECLARATIONS AND DEFINITIONS (2) Also like a variable declaration, a function declaration must appear above any use of the function’s name. But the function definition, when listed separately from the declaration, may appear anywhere outside the main() function and is usually listed after it or in a separate file. The variables that are listed in the function’s parameter list are called parameters. They are local variables that exist only during the execution of the function. Their listing in the parameter list constitutes their declaration. In the example above, the parameters are x and y. The variables that are listed in the function’s calls are called the arguments. Like any other variable in the main program, they must be declared before they are used in the call. In the example above, the arguments are m and n. In the example, the arguments are passed by value. This means that their values are assigned to the function’s corresponding parameters. So in the previous example, the value of m is assigned to x and the value of n is assigned to y. When passed by value, arguments may be constants or general expressions.

8 EX The max() Function with Declaration Separate from Definition This program is the same test driver for the same max() function as in previous example But here the function’s declaration appears above the main program and the function’s definition follows it: int max(int,int); // returns larger of the two given integers: int main() { // tests the max() function: int m,n; do { cin >> m >> n; cout << "\tmax(" << m << "," << n << ") = " << max(m,n) << endl; } while (m != 0); } int max(int x,int y) { if (x < y) return y; else return x; }

9 SEPARATE COMPILATION Function definitions are often compiled independently in separate files. For example, all the functions declared in the Standard C++ Library are compiled separately. One reason for separate compilation is “information hiding”— that is, information that is necessary for the complete compilation of the program but not essential to the programmer’s understanding of the program is hidden. Experience shows that information hiding facilitates the understanding and thus success of large software projects.

10 The max() Function Compiled Separately Test_max.cpp: int max(int,int); // returns larger of the two given integers: int main() { // tests the max() function: int m,n; do { cin >> m >> n; cout << "\tmax(" << m << "," << n << ") = " << max(m,n) << endl; } while (m != 0); } Max.cpp: int max(int x,int y) { if (x < y) return y; else return x; }

11 The Advantage of Separate Compiled Functions One advantage of compiling functions separately is that they can be tested separately before the program(s) that call them are written. Once you know that the max function works properly, you can forget about how it works and save it as a “black box” ready to be used whenever it is needed. This is how the functions in the math library are used. It is the “off-the-shelf software” point of view. Another advantage of separate compilation is the ease with which one module can be replaced by another equivalent module. For example, if you happen to discover a better way to compute the maximum of two integers, you can compile and test that function and then link that module with whatever programs were using the previous version of the max() function.

12 LOCAL VARIABLES AND FUNCTIONS A local variable is simply a variable that is declared inside a block. It is accessible only from within that block. Since the body of a function itself is a block, variables declared within a function are local to that function; they exist only while the function is executing. A function’s formal parameters (arguments) are also regarded as being local to the function.

13 The Factorial Function The factorial of a positive integer n is the number n! obtained by multiplying n by all the positive integers less than n: n! = (n)(n – 1) · · · (3)(2)(1) For example, 5! = (5)(4)(3)(2)(1) = 120. Here is an implementation of the factorial function: long fact(int n) { // returns n! = n*(n-1)*(n-2)*...*(2)(1) if (n < 0) return 0; int f = 1; while (n > 1) f *= n--; return f; } This function has two local variables: n and f. The parameter n is local because it is declared in the function’s parameter list. The variable f is local because it is declared within the body of the function. Here is a test driver for the factorial function: long fact(int); // returns n! = n*(n-1)*(n-2)*...*(2)(1) int main() { // tests the factorial() function: for (int i=-1; i < 6; i++) cout << " " << fact(i); cout << endl; }

14 void FUNCTIONS A function need not return a value. In other programming languages, such a function is called a procedure or a subroutine. In C++, such a function is identified simply by placing the keyword void where the function’s return type would be. int main() { // tests the printDate() function: int month,day,year ; do { cin >> month >> day >> year; printDate(month,day,year); } while (month > 0); }

15 void FUNCTIONS void printDate(int m,int d, int y) { // prints the given date in literal form: if (m 12 || d 31 || y < 0) { cerr << "Error: parameter out of range.\n"; return; } switch (m) { case 1: cout << "January "; break; case 2: cout << "February "; break; case 3: cout << "March "; break; case 4: cout << "April "; break; case 5: cout << "May "; break; case 6: cout << "June "; break; case 7: cout << "July "; break; case 8: cout << "August "; break; case 9: cout << "September "; break; case 10: cout << "October "; break; case 11: cout << "November "; break; case 12: cout << "December "; break; } cout << d << "," << y << endl; }

16 BOOLEAN FUNCTIONS In some situations it is helpful to use a function to evaluate a condition, typically within an if statement or a while statement. Here is a boolean function that determines whether an integer is a prime number: bool isPrime(int n) { // returns true if n is prime,false otherwise: float sqrtn = sqrt(n); if (n < 2) return false; // 0 and 1 are not primes if (n < 4) return true; // 2 and 3 are the first primes if (n%2 == 0) return false; // 2 is the only even prime for (int d=3; d <= sqrtn; d += 2) if (n%d == 0) return false; // n has a nontrivial divisor return true; // n has no nontrivial divisors }

17 Test drive program #include // defines the sqrt() function #include // defines the cout object using namespace std; bool isPrime(int); // returns true if n is prime,false otherwise; int main() { for (int n=0; n < 80; n++) if (isPrime(n)) cout << n << " "; cout << endl; }


Download ppt "Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize."

Similar presentations


Ads by Google