Presentation is loading. Please wait.

Presentation is loading. Please wait.

User-Written Functions

Similar presentations


Presentation on theme: "User-Written Functions"— Presentation transcript:

1 User-Written Functions
Lecture 12 Narrator: Lecture 12: User-Written Functions. Winter Quarter

2 User-Written Functions
So far, we have written only one function ourselves. That is function is called "main ( )". The syntax used has been as follows: void main ( ) { /* Declarations */ /* Statements */ } The word void means that the function is not expected to return any values to another function. Instructor: Some operating systems prefer instead of void main () to use int main () and the value returned gives a specific message to the operating system (or the user) to act upon. These numbers can correspond to messages such as the program terminated normally, a memory error occurred, the program was terminated by another signal, etc. Narrator: So far, we have only written one function for ourselves in our program. This is the main function. The syntax has always been as shown on the this slide. We haven’t really talked about the word void formally until now. Void means that the function doesn’t return any values to any other function. Some operating systems prefer instead of void main () to use int main () and the value returned gives a specific message to the operating system (or the user) to act upon. These numbers can correspond to messages such as the program terminated normally, a memory error occurred, the program was terminated by another signal, etc. Winter Quarter

3 User-Written Functions
The parentheses, ( ), both indicate that main is a function, AND provide a place for any variable names (arguments) that could be sent as values from another function. Since main is the main program function, it will normally not have a parameter list. (Who calls the main function anyway?) Most, but not all, other functions have parameter lists. Some such, as rand ( ), do not since they need no data or values from the calling function. Instructor: The user (or operating system in some cases) calls the main function of a program whenever it is run. It is possible to pass arguments to the main() function, but for the case of this class we normally do not. An example of passing variables to the main program is when the user adds options to a command prompt command such as ls –al where –al would be an option telling the program ls to list files in a special format. Narrator: The parentheses indicate that main is a function and provide a place for any variable names, or arguments as we have been calling them that could be sent as values from another function. Since main is the main program function, it will normally not have a parameter list in our case. The user (or operating system in some cases) calls the main function of a program whenever it is run. It is possible to pass arguments to the main() function, but for the case of this class we normally do not. An example of passing variables to the main program is when the user adds options to a command prompt command such as ls –al where –al would be an option telling the program ls to list files in a special format. Most, but not all, other functions have parameter lists, but some such as rand() don’t since they don’t need any data or values to complete their task. Winter Quarter

4 Writing User-Written Functions
There are typically three different types of statements needed to properly set-up and make use of a user-written function. They are: 1. The function prototype statement. 2. The first line of the function definition. 3. The calling statement. Instructor: These statements are described in the following slides. Narrator: Regarding user-written functions in general, there are typically three different types of statements needed to properly set-up and make use of a user-written function. These are: The function prototype statement, the first line of the function definition, and one or more calling statements. Winter Quarter

5 1. The Function Prototype Statement.
The function prototype's format is (note semicolon): return-value-type function-name (parameter-list) ;   The return-value-type may be any legal data type such as int, long, float, double, char, or it may be void. The parameter list is a list of data-types for the arguments and, optionally, the names of arguments. Example: float sum ( int , int , int ) ; /* OR */ float sum ( int a, int b, int c ) ; Instructor/Narrator: User-written functions are typically added after the main() function in a program for readability. The compiler then requires the function prototype since it parses the code from top to bottom. The compiler must know what functions exist before they are used, or else it will produce an error that it doesn’t know how to handle that function. The compiler basically cares about the function name and the input and output types since it only has to know what size and number of variables it will have to pass to the function (it cares about where they actually go later when it parses the function itself. Thus it is optional for the user to place the actual variable names in the function prototype’s arguments. Notice the function prototype looks identical to the first line of a function, with the addition of the semicolon at the end. Function prototypes are not needed if the entire function is placed before any other function the given function is called within. Thus placing all user-written functions before the main() function would eliminate the need of function prototypes. Winter Quarter

6 2. The First Line of the Function Definition.
The first line of the function definition is the same as the examples of the function prototype except that the SEMICOLON IS ELIMINATED and variable or argument NAMES ARE REQUIRED.  Example: float sum ( int a, int b, int c ) Here, the function sum is of type float and has three calling parameters, all of which are of type int. The variables a, b, and c take on the values of the variables or constants used in the calling statement. Instructor: The entire function is given on the next slide. Narrator: The first line of the function definition is nearly the same as the function prototype except the semicolon is removed and the rest of the function follows in braces. Also the argument names are required at this point. Winter Quarter

7 The Body of the Function
A complete function consists of the the function definition and the body of the function in the { }. Example: float sum ( int a, int b, int c) { float total; total = a + b + c ; return total; } Note: The function has return statement because it has a return type. Instructor: The return statement is required in any function which as a return type other than void. The return statement effectively quits execution of the function and returns whatever value the programmer tells it to, typically the value of a variable. Notice that inside the function only the total must be declared. The variables a, b, and c are already declared in the function’s first line and are initialized to the values passed to the function when it is called. Narrator: As stated previously, the body of the function then follows the function definition. An example of an entire function with the function definition and body is shown. In this function simply adds the three integers input and returns a floating point sum. The return statement is required in any function which as a return type other than void. The return statement effectively quits execution of the function and returns whatever value the programmer tells it to, typically the value of a variable. Winter Quarter

8 The Body of the Function
float sum ( int a, int b, int c) { int total; total = a + b + c ; return total; } The names a, b, and c are known only inside sum. Likewise, any variables, like total, declared within the function are local variables, and they are known only inside the function in which they are defined. Instructor: Emphasize that total is not known to the main() function, and that any changes made to a, b, and c in this case would only be known in the function (since only the value is passed to the function, not the original variable). This is explained more later. Narrator: The names declared in this function are only known WITHIN the function, likewise the variables normally declared in the function like total are called local variables and also known only within the function they are defined. All variables passed to a function are passed as copies of the original. Winter Quarter

9 3. The Calling Statement. The function call (or invocation) is like the first line of the function definition except NO DATA TYPES are shown and constants may be used instead of variable names. The valued returned by a function is normally assigned to a variable in the calling function. Example: value = sum ( i, j, k ) ; or value = sum ( 5, 6.73, 2 ) ; Instructor: This line is called inside another function (main() for example). This actually calls the function like one would call rand() or printf() or any other function with the arguments as shown. Since this function returns a number the value is used as the result of the function, and in this case placed in a variable called value. Narrator: The calling statement is where the function is actually used in the program. It is used the same as any other function, with the values passed as arguments, and if a value is returned, the function can be set equal to another variable. Some examples are shown here, and could be included as statements in a main() function for example. Winter Quarter

10 Factorial Function Main Program
#include <stdio.h> long factorial ( int x ) ; void main ( ) { int k; for ( k=0 ; k<=10 ; k++ ) printf ("%2d factorial is %ld\n", k , factorial (k) ) ; } Instructor: This program contains a user-written function which computes factorials and a main function which calls the factorial function for numbers 0 to 10. Notice the function prototype before the main () with the appended semicolon, and its similarity to the actual function on the next slide. Also point out where the function is used in the printf() function as a value, since the factorial function returns a type long value. Narrator: This program contains a user-written function which computes factorials and a main function which calls the factorial function for numbers 0 to 10. Notice the function prototype before the main () with the appended semicolon, and its similarity to the actual function on the next slide. Also notice where the function is used in the printf() function as a value, since the factorial function returns a type long value. Winter Quarter

11 Factorial Function long factorial ( int x ) { long fact = 1; int k;
if ( x < 0 ) return 0; else if ( x==0 || x==1 ) return 1; else for ( k = 2 ; k <= x ; k++ ) fact = fact * k ; return fact ; } Instructor: This function calculates a factorial for any number passed to it. The number passed to the function is stored in “x”, and the value returned is calculated and stored in “fact”. Narrator: This function calculates a factorial for any number passed to it. The number passed to the function is stored in “x”, and the value returned is calculated and stored in “fact”. Notice how the function declaration looks much like the function prototype, and a value is returned in this case. Winter Quarter

12 Factorial Program Output
0 factorial is 1 1 factorial is 1 2 factorial is 2 3 factorial is 6 4 factorial is 24 5 factorial is 120 6 factorial is 720 7 factorial is 5040 8 factorial is 40320 9 factorial is 10 factorial is Instructor: The result of the factorial program. This may be compared to a calculator’s output. Narrator: This is the output of the factorial program. The factorial function is called multiple times and produces results comparable to a calculator. One can see how the use of a function in this case is useful since a programmer can re-use common code to complete the same task multiple times. Winter Quarter

13 User-Written Functions (example):
#include <stdio.h> void swap ( int a, int b ) ; void main ( ) { int a = 5, b = 6; printf ("a=%d b=%d\n",a,b); swap (a, b); } void swap ( int a, int b ) { int temp; temp = a; a = b; b = temp; printf ("a=%d b=%d\n", a, b ); } a=5 b=6 a=6 b=5 Instructor/Narrator: This program is actually two columns of code. The main() function is given on the left and the user-written function on the right. The output of the program is given in the bottom right. This program demonstrates that values passed to a function are actually passed as copies of the values, and not the original values themselves. The first line of output is from the main function where the values are initialized. The values are passed to a swap function which swaps the values and displays them inside the function, but DOES NOT pass them back to the main function. After this the main function completes execution and displays the values it knows for a and b, which remain unchanged. When functions are called, ALL of their variables are given their own unique memory space, and copies of the values passed to the function are automatically stored in the function’s memory. In this case the only way to get values out of the function are to return them. Another way is to pass the original location of the variables in memory to the function as variables, which will be discussed later. Winter Quarter

14 Call By Value vs. Call By Reference
Two ways in which variables are passed: Call by value Call by reference "Call by value" means function only gets a copy of the value of the calling argument. The called function can not change the value back in the calling routine. This is normally how it is in C. "Call by reference" means the function gets the original argument, and thus the called function can change the value of the variable back in the calling routine. Must use pointers in C to do this. Instructor: Call by value is what occurs in this lecture. Call by reference will be described in detail when pointers are introduced. For now students only need to know another method exists that will solve this problem. Narrator: There are two ways we can pass variables to functions. The way we have been passing them is known as call by value, where we pass the value of variables themselves. In this manner the function gets a copy of the value and can’t change the original variable that is known by the calling function. Another method is known as call by reference, which passes the address of the original variable as an argument. Pointers are required for this to occur, which will be discussed in Lecture 14. Winter Quarter


Download ppt "User-Written Functions"

Similar presentations


Ads by Google