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.
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
type name ( arguments ) { body }
double sqr(double x) { return x*x; }
return any_expressionThe 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 )
cout << sqr(4) << endl;
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)); }
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
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; .....)
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.
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.
. . . . . . . . . ( end of section Functions in C++) <<Contents | End>>
Questions
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:
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;
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.
. . . . . . . . . ( end of section Exercises) <<Contents | End>>
Next -- More functions with Quiz 5 Lab 6 Project 4
[ projects.html#P4 ]