Lecture 4

54
AU/MITM/1.6 By Mohammed A. Saleh 1

description

Functions (I) in C++

Transcript of Lecture 4

Page 1: Lecture 4

AU/MITM/1.6

By Mohammed A. Saleh

1

Page 2: Lecture 4

Test 1 Date : 24th March, 2009 Day : Friday Venue : Lab 5 (4th Floor) Time : 90 minutes

DO NOT MISS …!!!

2

Page 3: Lecture 4

(*missing slides*) The indivisible elements in a line of code are

called tokens. Generally, you must separate one token from

the next with a space, tab, or carriage return, which collectively are termed white space.

3

Page 4: Lecture 4

Figure 1.0: Tokens and White Space.

4

Page 5: Lecture 4

Some single characters, such as parentheses and commas, are tokens that need not be set off by white space. Examples:return0; return(0); return (0); intmain(); int main() int main ( )

5

Page 6: Lecture 4

Functions are the modules from which C++ programs are built. Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++.

A function is a group of statements that is executed when it is called from some point of the program.

C++ functions come in two varieties: those with return values and those without return values

6

Page 7: Lecture 4

Using a Function That Has a Return Value A function that has a return value produces a

value that you can assign to a variable. For example, the standard C++ library includes a function called sqrt() that returns the square root of a number.

Suppose you want to calculate the square root of 6.25 and assign it to the variable x. You can use the following statement in your program: 7

Page 8: Lecture 4

x = sqrt(6.25); // returns the value 2.5 and assigns it to x

The expression sqrt(6.25) invokes, or calls, the sqrt() function. The expression sqrt(6.25) is termed a function call, the invoked function is termed the called function, and the function containing the function call is termed the calling function.

8

Page 9: Lecture 4

The value in the parentheses is information that is sent to the function; it is said to be passed to the function. A value that is sent to a function this way is called an argument or parameter 9

Page 10: Lecture 4

The sqrt() function calculates the answer to be 2.5 and sends that value back to the calling function; the value sent back is called the return value of the function.

Before the C++ compiler uses a function, it must know what kind of arguments the function uses and what kind of return value it has. Does the function return an integer? a character? a number with a decimal fraction?

10

Page 11: Lecture 4

If it lacks this information the compiler might not know how to interpret the return value. The C++ way to convey this information is to use a function prototype statement.

A function prototype does for functions what a variable declaration does for variables: It tells the compiler what types are involve.

The function prototype for sqrt() looks like this:

11

Page 12: Lecture 4

double sqrt(double); // function prototype The initial double means sqrt() returns a type

double value. The double in the parentheses means sqrt() requires a double argument. So this prototype describes sqrt() exactly as used in the following code:

double x; // declare x as a type double variable x = sqrt(6.25);

12

Page 13: Lecture 4

Every function in the C++ library has one or more header files. For example, the description of the sqrt() function should tell you to use the cmath header file.

Example:

13

Page 14: Lecture 4

// sqrt.cpp -- using the sqrt() function #include <iostream> #include <math> // or math.h int main() {double area; cout << “Enter the floor area, in square feet, of your home: “; cin >> area; double side; side = sqrt(area); cout << “That’s the equivalent of a square “ << side << “ feet to the side.” << endl; cout << “How fascinating!” << endl; return 0; } 14

Page 15: Lecture 4

A sample run of the program:Enter the floor area, in square feet, of your home: 1536That’s the equivalent of a square 39.1918 feet to the side. How fascinating!

Function Variations Some functions require more than one item

of information. These functions use multiple arguments separated by commas.

15

Page 16: Lecture 4

For example, the math function pow() takes two arguments and returns a value equal to the first argument raised to the power given by the second argument.

It has this prototype:double pow(double, double); /* prototype of a function with two arguments */

Other functions take no arguments. The rand() function that has no arguments and that returns a random integer. 16

Page 17: Lecture 4

Its prototype looks like this:int rand(void);

// prototype of a function that takes no arguments The keyword void explicitly indicates that

the function takes no argumentsUser-Defined Functions C++ allows a programmer to create and

design his/her own functions.

17

Page 18: Lecture 4

You must provide a function prototype before using the function, which you typically do by placing the prototype above the main() definition.

The new element is that you also must provide the source code for the new function. The simplest way is to place the code in the same file, after the code for main().

Example:18

Page 19: Lecture 4

// ourfunc.cpp -- defining your own function#include <iostream> void simon(int); // function prototype for simon() int main() {simon(3); // call the simon() function cout << “Pick an integer: “; int count; cin >> count; simon(count); // call it again cout << “Done!” << endl;return 0; } void simon(int n) // define the simon() function {cout << “Simon says touch your toes “ << n << “ times.” << endl; } // void functions don’t need return statements

19

Page 20: Lecture 4

Sample run of the program:Simon says touch your toes 3 times. Pick an integer: 512 Simon says touch your toes 512 times.Done! The main() function calls the simon()

function twice, once with an argument of 3 and once with a variable argument count.

20

Page 21: Lecture 4

Function Formtype name ( parameter1, parameter2, ...) {

statements } Where:-• type is the data type specifier of the data

returned by the function.• name is the identifier by which it will be

possible to call the function.21

Page 22: Lecture 4

• parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

22

Page 23: Lecture 4

• statements is the function's body. It is a block of statements surrounded by braces { }.

Using a User-Defined Function That Has a Return Value An example program to convert stones to

pounds. It uses a function for this conversion.

23

Page 24: Lecture 4

// convert.cpp -- converts stone to pounds #include <iostream>int stonetolb(int); // function prototype int main() {int stone;cout << “Enter the weight in stone: “; cin >> stone; int pounds = stonetolb(stone); cout << stone << “ stone = “; cout << pounds << “ pounds.” << endl; return 0; } int stonetolb(int sts) { return 14 * sts; } 24

Page 25: Lecture 4

Figurer 2.0: The function prototype and the function as a black box

The stonetolb() function is short and simple, yet it embodies a full range of functional features:

25

Page 26: Lecture 4

It has a header and a body. It accepts an argument. It returns a value. It requires a prototype. Consider stonetolb() as a standard form for

function design. Another example:

26

Page 27: Lecture 4

// function example#include <iostream>int addition (int a, int b) ; // function prototype

int main (){ int z; z = addition (5,3); cout << "The result is " << z; return 0;}int addition (int x, int y){ // function definition int r; r = x +y;return (r);}

27

Page 28: Lecture 4

C++ program always begins its execution by the main function.

The main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition.

int addition ( int a, int b)

z = addition ( 5 , 3 )

28

Page 29: Lecture 4

The parameters and arguments have a clear correspondence.

Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition.

When the function is called from within main, the control is lost by main and passed to function addition.

29

Page 30: Lecture 4

The value of both arguments passed in the call (5 and 3) are copied to the local variables int a and int b within the function.

Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b.

Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.

30

Page 31: Lecture 4

The following line of code:return (r);

finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main).

At this moment the program follows it regular course from the same point at which it was interrupted by the call to addition.

31

Page 32: Lecture 4

But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call.

int addition ( int a, int b) 8z = addition ( 5 , 3 )

32

Page 33: Lecture 4

So being the value returned by a function the value given to the function call itself when it is evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8.

Scope of Variables The extent of which a variable can be used in

a program.

33

Page 34: Lecture 4

The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them.

For example, in the previous example it would have been impossible to use the variables a, b or r directly in function main since they were variables local to function addition.

34

Page 35: Lecture 4

Also, it would have been impossible to use the variable z directly within function addition, since this was a variable local to the function main.

35

Page 36: Lecture 4

36

Page 37: Lecture 4

Therefore, the scope of local variables is limited to the same block level in which they are declared.

Nevertheless, we also have the possibility to declare global variables; These are visible from any point of the code, inside and outside all functions

In order to declare global variables you simply have to declare the variable outside any function or block 37

Page 38: Lecture 4

// function example#include <iostream>

int subtraction (int a, int b) ; int main (){ int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0;}Int subtraction (int i, int n){ int r; r=i-n; return (r); } 38

Page 39: Lecture 4

In this case we have created a function called subtraction. The only thing that this function does is to subtract both passed parameters and to return the result.

Nevertheless, if we examine function main we will see that we have made several calls to function subtraction

Some different calling methods so that you see other ways or moments when a function can be called. 39

Page 40: Lecture 4

Consider once again that a call to a function could be replaced by the value that the function call itself is going to return. For example, the first case:

If we replace the function call by the value it returns (i.e., 5), we would have:

40

z = subtraction (7, 2)cout << “ The first result is “ << z ;

z = 5cout << “ The first result is “ << z ;

Page 41: Lecture 4

As well as:

has the same result as the previous call, but in this case we made the call to subtraction directly as an insertion parameter for cout.

Simply consider that the result is the same as if we had written:

since 5 is the value returned by subtraction (7,2). 41

cout << "The second result is " << subtraction (7,2);

cout << "The second result is " << 5;

Page 42: Lecture 4

In the case of:

The only new thing that we introduced is that the parameters of subtraction are variables instead of constants. That is perfectly valid. In this case the values passed to function subtraction are the values of x and y, that are 5 and 3 respectively, giving 2 as result.

42

cout << "The third result is " << subtraction (x,y);

Page 43: Lecture 4

The fourth case is more of the same. Simply note that instead of:

We could have written:

with exactly the same result.

43

z = 4 + subtraction (x,y);

z = subtraction (x,y) + 4;

Page 44: Lecture 4

Function ReviewRecall: To use a C++ function, you must do the

following: Provide a function definition Provide a function prototype Call a function An example program to emphasize the three

aspects: 44

Page 45: Lecture 4

// calling.cpp -- defining, prototyping, and calling a function #include <iostream>void simple(); // function prototypeint main() {cout << “main() will call the simple() function:\n”; simple(); // function call return 0; } // function definition void simple() {cout << “I’m but a simple function.\n”; } 45

Page 46: Lecture 4

Prototyping and Calling a Function A function example showing the cheers() and

cube() functions used in a program; notice the function prototypes.

46

Page 47: Lecture 4

// protos.cpp -- using prototypes and function calls #include <iostream> void cheers(int); // prototype: no return valuedouble cube(double x); // prototype: returns a double int main(void) {cheers(5); // function call cout << “Give me a number: “; double side; cin >> side; double volume = cube(side); // function call cout << “A “ << side <<”-foot cube has a volume of “; cout << volume << “ cubic feet.\n”;cheers(cube(2)); // prototype protection at work return 0; }

47

Page 48: Lecture 4

void cheers(int n){

for (int i = 0; i < n; i++)cout << “Cheers! “; cout << endl;

}

double cube(double x){

return x * x * x; }

48

Page 49: Lecture 4

Sample run:Cheers! Cheers! Cheers! Cheers! Cheers! Give me a number: 5 A 5-foot cube has a volume of 125 cubic feet.Cheers! Cheers! Cheers! Cheers! Cheers! Cheers! Cheers!

Cheers!

49

Page 50: Lecture 4

Why Prototypes? You need to understand why C++ needs

prototypes only then you will be able to know the proper syntax.

As we know, a prototype describes a function interface to the compiler, i.e it tells the compiler what is the return value, if any, and it also tells the compiler the number and type of function arguments.

Consider : double volume = cube(side); 50

Page 51: Lecture 4

Prototype Syntax A function prototype is a statement, so it

must have a terminating semicolon.double cube(double x); In particular prototypes ensure the following: The compiler correctly handles the function

return value. The compiler checks that you use the correct

number of function arguments.51

Page 52: Lecture 4

The compiler checks that you use the correct type of arguments. If you don’t, it converts the arguments to the correct type, if possible.

Suppose you provide an argument but it is the wrong type.

For example, if a function expects a type int value (assume that’s 16 bits) and you pass a double (assume that’s 64 bits). the function looks at just the first 16 bits of the 64 and tries to interpret them as an int value 52

Page 53: Lecture 4

Consider:cheers (cube(2))

First, the program passes the int value of 2 to cube(), which expects type double. The compiler, noting that the cube() prototype specifies a type double argument, converts 2 to 2.0, a type double value.

Then, cube() returns a type double value (8.0) to be used as an argument to cheers().

53

Page 54: Lecture 4

Again, the compiler checks the prototypes and notes that cheers() requires an int. It converts the return value to the integer 8.

In general, prototyping produces automatic type casts to the expected types.

54