[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [CSci201] / 10
[Text Version] [Syllabus] [Schedule] [Glossary] [Labs] [Projects] [Resources] [Grading] [Contact] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] <10> [11] [12] [13] [14] [15] [16] [17] [18] [19] [20]
Podcasts: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10]
Labs: [01] [02] [03] [04] [05] [06] [07] [09] [10]
Thu Feb 7 15:23:18 PST 2008

Contents


    Chapter 4 pages 109-119 Functions

      Reading on Functions

        Introduction

        This section is also be available at [ 10.mp3 ] as a podcast.

        Welcome to the 10th reading in CS201 Winter 2008. This introduces a powerful tool that all programmers must be able to use. These are called functions and procedures. They are a way of avoiding repeated code and a way to share code with other programs and programmers. The C++ libraries are collections of functions.

        Functions are very important. You can not write a program without writing one and most programs can be improved by introducing a new one. The moment you have written two similar pieces of code you should think about putting the repeated code in a function and calling it twice instead.

        Indeed a programming language that has functions and if-statements can compute any function that can be computed -- this is proved in the senior level computer science courses.

        This piece of the text is about functions that are like the functions of mathematics. They take in some data and return a value. You have already used functions like sin, cos, sqrt, exp, and log. But C++ functions can do a lot more than the functions of classical mathematics. With them you can create a short expression for a complex calculation.

        Notice that when you call a function with expressions for arguments then these arguments are always evaluated first and the values are then passed to the function. It follows that when you write an expression with one function calling another you must work out the result inside-out. If you write sqrt(exp(sin(2))) then the computer starts by evaluating the sin of 2, and then the exponential of that number, and then, finally it gets back to the sqrt function. As always you have to carefully work out what an expression does rather than guess.

        1. page 110 -- how to declare functions
        2. page 111 -- how to return a result
        3. page 111 -- main is where the program starts
        4. page 113 -- How to call a function
        5. page 113 -- the classic max function
        6. page 114 -- the classic strlen function
        7. page 115 -- the classic sum function
        8. page 117 -- the classic binary search function
        9. page 118 -- forcing the user to supply a number

        I'm also going to add some notes on the web page on determining where variables can be used in a C++ program. This is what Scope means. I also want to define what a Block is.

        Please study the web page!

        4.1 Functions returning a value

          page 110 -- how to declare functions

           	type name ( arguments ) { body }

          1. The type is any type of data: int, char, double, bool, string, ...
          2. The arguments is a list of variable declarations: type name, type name,...
          3. The body is any sequence of statements.
          4. The parentheses (...) and braces {...} are essential.

           double sqr(double x) { return x*x; }

          page 111 -- how to return a result

           		return any_expression
          The expression is evaluated and if necessary changed to the right type before being returned as the value of the call.
           			return x*x;

          Common mistake: the returned values are not printed out by return.

          page 111 -- main is where the program starts

          The main(){ .... } that we have been writing in our programs is just like a function that is called by the operating system when the program starts executing, and returns an int when the program finishes executing back to the operating system.

          Notice that if the type of function is omitted then the compiler assumes that the function returns an int

          page 113 -- How to call a function

           	name ( actual_arguments )

          1. The actual arguments are expressions that are evaluated before the body of the function starts executing.
          2. The function cal is an expression that returns a value

           			cout << sqr(4) << endl;

          page 113 -- the classic max function

          Can you copy and edit this function so that it returns the minimum of two items?

          You might like to input, test, and keep a copy of this function for future use.

          page 114 -- the classic strlen function

          Only used in the old C language -- but a nice example.

          page 114 -- Functions that call other functions

          It is normal for functions in expressions to call other functions Always work out values of functions inside-out... [ funfun.cpp ]
           			cout << sqrt(sqr(3)+sqr(4)) << endl;

          This can happen inside a function as well:

           double pyth(double x, double y) { return sqrt(sqr(x)+sqr(y)); }

          page 115 -- the classic sum function

          This one is worth remembering.

          You might like to input, test, and keep a copy of this function for future use.

          page 117 -- the classic binary search function

          Another classic.... but no need to memorize it until CSCI202.

          page 118 -- forcing the user to supply a number

      . . . . . . . . . ( end of section Reading) <<Contents | End>>

      Block

        A block is a piece of code that (1) starts with an open brace "{" and (2) finishes with a close brace "}" and (3)contains variable declarations. A block can contain any number of declarations and statements. It can also have blocks in it because "{" and "}" create a single statement.

        Variables that are declared in a block are local to that block. They can not be referred to outside that block.

        More ... you can declare a new variable with the same name as an old variable inside an inner (nested block). The new variable can have a different type as the outer one. The compiler keeps them separate.

        The for loop can also act as the start of a block if it declares a variable:

         		for( Type variable = initial_value; .....)

      Scope

        The scope of a declaration is the set of statements in which it applies in a program. The scope can be as large as a complete program or as small as a single block. It depends where the declaration occurs. If it is outside any blocks -- where functions are typically declared -- then they have global scope and are potentially available in every part of the program. If a variable or constant is declared inside a block then the scope is no more than that block. The declaration is forgotten when the close brace appears.

        When a name is redeclared inside an inner block then this introduces a new meaning that overrides the outer declaration until the new meaning is ended at the end of its block. So the scope of a declaration consists of the block in which it is declared minus all the inner blocks where the same name is redeclared.

        The scope of a variable declared in a for loop

         		for( Type variable = initial_value; .....)
        is the statement which the for statement repeats -- minus any inner declarations.

        Notice that the variable declared in a for loop vanishes at the end of the body of the loop.

        Notice that this means that a sequence of un-nested for loops can all use the same variable with out any problems.

        These rules look complicated. But they have a very nice effect. You can figure out the meaning of a variable, function, or constant be working back to the nearest declaration. Previous (outer) ones do not matter.

      Testing Functions

      When ever you do a project that calls for you to write a function you must also write a main program that tests the value of the function for several different argument values. Submit the whole program.

      Functions in C++

        Introduction

        This is a quick summary of some things you may need to know about C++ functions at the CS201 (CS1) level. With out these facts you will make more mistakes and will not be able to use the full power of C++ to make your programming easier.

        Basics

        A C++ function is a sub-program. It is a small, named piece of a program that is called up from other parts of the same program.

        A function must be defined once and can be called any number of times. A function has a name, arguments, and a body. A common problem with programs is that a function call can not be matched up to any function in the rest of the program.

        The body is compiled and stored in memory. When the call is executed the computer jumps to the start of the body. Once in the body it executes its code until it gets to the end or a 'return' statement. If it executes an "exit" statement the whole program terminates. If the computer gets to a return or the end of the function then it jumps to the instruction in the program immediately after the call.

        The Main Function

        All executable programs must have a special function with name "main" and special arguments. The program run starts when the operating system calls this "main" function.

        The main program should return an positive int that indicates if any errors have been discovered by the program. The number zero indicates that zero errors have occurred. A number other than zero indicates that the program did not complete its task and the precise number often is used to indicate the reason for the program failing. The operating system can find out the number the main program returns.

        Compilation

        The compiler has to match up the function call with the right function. It uses the name of the function plus the number and type of the arguments in the call. to find a matching function. If no function is found that has the right name and arguments then the compiler reports an error and the program can not be run.

        A function definition has two parts: a header and a body. The header specifies how the function can be called. The body defines what happens if and when the function is called. We say that the header specifies the function. The complete body and header is said to be an implementation of the function.

        In C++ there is a special syntax for giving the header without defining the body: The body is replaced by a semicolon. The result is called a function prototype, or specification. A file that contains a series of function prototypes is called a header file. Typically a compiler learns about the functions you plan to use in a program file by compiling a series of these header files #included at the start of the program. These are often predefined library files that come with the compiler. Here, for example, [ cmath.txt ] is a simplified version of the <cmath> library.

        Return Values

        A function header can specify that a value must and will be returned by a function. If so there must be one or more return_statement's that contain an expression. If the expression is executed than the expression is evaluated and the value left behind (on the runtime stack) for the calling program to collect and use.

        Overloading

        A C++ function is matched, by the compiler+linker, to its calls by using both its name and the types of its arguments. So the same name can be used for several similar functions with different types of data.

        This works well as long as the names you choose actually reflect what the functions do.

        Jargon and Glossary

        1. int::data_type=used to store integers -- whole numbers, use for counting things.
        2. float::data_type=used for real numbers when precision is not important, good for old or small computers.
        3. double::=data_type=used for real numbers when precision is important, use for all measurements.
        4. char::data_type=used to store a single 7, 8 or 9 bit character.
        5. string::data_type=used to store a sequence of numbered char.

        6. data_type::=a collection of objects that are stored in similar formats and have the same operations and operators.
        7. function_header::=the part of the function that comes first and describes how to call it.
        8. function_body::=the part of a function between braces that is after the header.

      . . . . . . . . . ( end of section Functions in C++) <<Contents | End>>

      Questions

        Can you explain Binary Search

        Binary search search a collection of items by dividing them in half and then picking one half to search. It is a common example of a divide and conquer algorithm. You can use the algorithm to search anything that is in the right order. The white pages of a telephone directory is one example. To find a name in the directory, you put your finger in the middle of the directory. The name is either before or after your finger. Pick the correct half. Again, divide the pages you are search into two halves, and pick the right half. Continue until the page you want is in front of you.

        Try it on any order list, array, or vector...

        What is the purpose of functions that return a value

        They defines a short hand way of doing a long calculation. You can get the calculation by just calling the function. You can share it with other people as well.

        Are there an infinite number of functions in C++

        There is a potential for an infinite number, but any given program can only have a finite number.

        Is there any limit on the number of functions

        No.

        Can you put if and while inside a function

        Yes.

        Can you define a function inside a function

        No.

        Can we use functions in place of anything

        I guess so.

        In simple words what is a function

        A named piece of code that you can use many times in many ways.

        How are functions declared

        Functions a declared by writing the header:
      1. type_of_data_returned name_of_functions ( parameters )

        From then on (but not before) you can use that function in the program. More in the next class on this topic.

        Can you explain the fmod function

        Here is a working program [ fmod.cpp ] that demonstrates what it does.

        Whay are there only functions and no procedures in C++

        The inventors of C thought it was a good idea to only have functions. If you didn't say what was returned, it would be an int.

        When they standardized C they let people use the word "void" to indicate functions that didn't return a useful result. So procedures are called void functions in C++.

        What is return

        Return is a statement that gives control back to the calling code. The computer leaves the function and continues from the statement or expression after the call. The return can also calculate and return a value.

        How do I use return

        First plan an algorithm for the function.... where it has a result and finishes.... you have a place in the code to write
         		return result;

        Do you declare functions before main

        Yes.

        You have to because you can only use a function after the compiler has seen a declaration (the header) of the function. Before then the call will not compile.

        Can functions produce non-numerical results

        Yes. Functions that return bool are good for testing and are called predicates. Functions returning strings and characters are also useful. Beware, however, of returning arrays from a function. The results are not good.

        How do functions use parameters

        First they evaluate them. Then they move the values to the initialize the formal parameters -- just as if they are local variables.

        More on this in the next lecture/discussion.

        What is a block

        A function with no name! More oficially it starts "{" and ends "}" and has at least one declaration.

        How can variables be declared in blocks

        Just like they are declared in the main program.

        Can things be declared outside a block

        Yes.

        Functions must be outside a block (with a couple of exceptions mentioned later this quarter).

        Variables can be declared outside a block. They are called global variables and are a very dangerous feature seeing that any function can change their values without any sign of the change occuring.

        Constants can be defined out side a block and are called gobal constants and are a very good way to define natural constants and numbers. The classic example being

         const double PI = 4*atan(1);
        Here is another:
         const int DAYSINWEEK = 7;
        These are cmputed before the program starts and can be used safely anywhere in the program. Notice that constants should be in capital letters.

      Exercises

        Handout [ 10ex.cpp ] -- what does it do. DO NOT GUESS. WORK IT OUT, STEP BY STEP, in pairs.

      . . . . . . . . . ( end of section Exercises) <<Contents | End>>

      Next -- More functions with Quiz 5 Lab 6 Project 4

        [ lab06/ ]

        [ projects.html#P4 ]

    Abreviations

  1. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular C++ compiler.
  2. KDE::="Kommon Desktop Environment".
  3. TBA::="To Be Announced", something I should do.
  4. TBD::="To Be Done", something you have to do.
  5. UML::="Unified Modeling Language", [ uml.html ] (beginner's introduction to the UML).

End