340 likes | 436 Views
Chapter 5. Functions. What is a function?. A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program. The most important reason to use functions is to aid in the conceptual organization of a program.
E N D
Chapter 5 Functions
What is a function? • A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program. • The most important reason to use functions is to aid in the conceptual organization of a program. • Dividing a program into functions is one of the major principles in structured programming.
What is a function? • Another reason to use functions (and the reason they were invented) is to reduce program size. • Any sequence of instructions that appears in a program more than once is a candidate for being made into a function. • The functions code is stored in only one place in memory, even though it is executed many times in the course of a program.
Calling Program func1(); Function Void func1() { \\ Code } Calls to function func1(); func1(); Same code is used for all calls to function.
Simple Functions • Our first example demonstrates a simple function whose purpose is to print a line of 45 asterisks. The example program generates a table, and lines of asterisks are used to make the table more readable. • Let’s look at this example, table.cpp
Simple Functions • That sample program consists of two functions: main() and starline(). • There are 3 necessary components for adding a function to a program. 1. The function declaration 2. The calls to the function 3. The function definition
The Function Declaration • Just as you can’t use a variable without first telling the compiler what it is, you can’t use a function without telling the compiler about it. • There are 2 ways to do this, declare the function before it is called (as in our example) and to define it before it is called (we will see this later).
The Function Declaration • In our table.cpp program we declared the function starline() in the line “void starline();” • This declaration tells the compiler that at some point we plan to present a function called starline. • The keyword void specifies that the function has no return values, and the empty parentheses indicate that it takes no arguments. (We could also put the keyword void inside of the parentheses but it is more common just to leave them blank.)
The Function Declaration • Notice also that the function declaration is terminated by a semicolon “;”. This is a complete statement in itself. • Function declarations are also called prototypes, since they provide the model or blueprint for the function. This tells the compiler that later in the program we are using a function and we show it what this function will look like.
Calling the Function • The function is called three times from main() in our example program. Each of the three calls look like “starline();”. • This is all that we need to call the function: the function name, followed by parentheses. • Executing this call statement causes the function to execute.
Calling the Function • When a function is called these are the steps a computer will take: • The call statement causes the function to execute, control of the program goes from the main() function to the called function. All variables are written into memory and the computer keeps track of what part of the program it left off and went to the function. The function called is then executed and once done, the control goes back to main, those variables are loaded from memory and the main function continues from where it left off.
The Function Definition • Lastly the function itself is the function definition. • The definition contains the actual code for the function. • The definition consists of a line called the declarator (void starline()), followed by the function body. • The function body is made up of statements that make up the function delimited by braces.
The Function Definition • The declarator must agree with the declaration. In other words your function definition should match exactly to where you declared your function. • The function definition is not terminated by a semi-colon “;” as the declaration is.
The Function Definition • When the function is called, control is transferred to the first statement in the function body. • The other statements in the function body are then executed, and when the closing brace is encountered, control returns to the calling program.
Component Purpose Example Declaration Specifies function name, argument void func(); (prototype) types, and return values. Alerts compiler that a function is coming up later. Call Causes the function to be executed. func(); Definition The function itself. Contains the lines void func() of code that constitute the function. { // code } Declarator First line of definition void func()
Comparison with Library Functions • We have already seen some library functions in use. One function is called rand(); • rand function i = rand(); • Load <cstdlib> • Generates a pseudorandom number between 0 and RAND_MAX (usually 32767) • A pseudorandom number is a preset sequence of "random" numbers • The same sequence is generated upon every program execution
Comparison with Library Functions • srand function • Jumps to a seeded location in a "random" sequence srand( seed ); srand( time( NULL ) ); //must include <ctime> • time( NULL ) • The time at which the program was compiled/run • Changes the seed every time the program is run, thereby allowing rand to generate random numbers
Comparison with Library Functions • When we used these random number functions where are the declaration and definitions for these library functions? • The declaration is in the header file specified at the beginning of the program. (<cstdlib>) • The definition (compiled) is in a library file that’s linked automatically when you build your program.
Comparison with Library Functions • When we use a library function we don’t need to write the declaration or definition. But when we write our own functions, the declaration and definition are part of our source file. • We could make our own header file and compile source code of just functions.
Eliminate the Declaration • The second approach to inserting a function into a program is to eliminate the function declaration and place the function definition (the actually function itself) in the listing before the first call to the function. • Let’s go back and look at our last example but with no function declaration. table2.cpp
Eliminate the Declaration • This second approach is simpler for short programs because it removes the declaration, but it is less flexible. • There are problems with this arrangement. • For this to work you need to write the function before you use it. Sometimes this is impossible because some functions will rely on other functions.
Eliminate the Declaration • In general we will avoid this way of eliminating the declaration and instead use a declaration and define the function after the main() function. • It is easier to read code if main is first and is more logical to read this way.
Passing Arguments to Functions • An argument is a piece of data (an int value for example) passed from a program to the function. • Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.
Passing Constants • Lets go back to our example • This time lets allow the function starline() to print any character any number of times. • Remember that so far this function just prints out 45 astrisks “*”. • Lets look at tablearg.cpp
Passing Constants • The new function is called repchar(), it’s declaration looks like: • void repchar(char, int); • The items in the parentheses are the data types of the arguments that will be sent to repchar(); char and int.
Passing Constants • In a function call, specific values, constants in this case are inserted in the appropriate place in the parentheses. • repchar(‘-’, 43); // function call • This statement instructs repchar() to print a line of 43 dashes. The values in the call need to match the types in the definition.
Passing Constants • The calling program supplies the arguments, such as ‘-’ and 43 to the function. • The variables used within the function to hold the argument values are called parameters; in repchar() they are ch and n.
Passing Variables • In the last example the arguments were constants: ‘-’, 43 and so on. • This isn’t very useful to have constants but would be very helpful to have variables instead. • Lets look at the program vararg.cpp that will let the user to specify the character to print and the number of times it should be repeated.
Passing Variables • In our last example, chin and nin in main() are used as arguments to repchar(). • Repchar(chin, nin); // function call • The data types of variables used as arguments must match those specified in the function declaration and definition. In other words, chin must be a char, and nin must be an int.
Passing by Value • In our last example the values that were stored in chin and nin when the function call is executed will be passed to the function. • When the function is called it creates new variables to hold the values of these variable arguments.
Passing by Value • The function gives these new variables the names and data types of the parameters given to the function. • In this example in the function, new variables are are created, ch of type char and n of type int. • Then these 2 variables are initialized to those values passed to the function. • And then these variables can be accessed just as any other variable.
Passing by Value • When you pass arguments in this way, where the function creates copies of the arguments passed to it, is called passing by value. • Let’s look more visually at this process.
Repchar(chin, nin); This statement in main() causes the values in these variables to be copied into these parameters in repchar(). main() repchar() ch chin ‘=‘ ‘=‘ nin n 30 30 Arguments Parameters
Structures and Return Values • We can also pass structures to functions. • We can also return values from functions back to the main function. • We will look at these issues and more next time.