Sie sind auf Seite 1von 32

Functions (Part II)

QF002/8/1

UNIT 8

FUNCTIONS (Part II)

OBJECTIVES
General Objective :

To understand and apply the principles of function in programming.

Specific Objectives

At the end of the unit you should be able to: -

 Use Function In A Program  Write And Design A Simple Function Of A Program.  Describe The Passing Argument To A Function.  Apply Function Prototypes In A Program

Functions (Part II)

QF002/8/2

INPUT

8.0

Introduction

What is function ? A function is a subprogram that can act on data and return a value .

note

The function definition must match the function prototype in return type, name, and parameter list. Function names can be overloaded by changing the number or type of parameters; the compiler finds the right function based on the argument list.

 Each function has its own name and when that name is en countered, the execution of the program branches to the body of that function. When the function returns, execution resumes on the next line of the calling function. This flow is illustrated in Figure 8.1.

Functions (Part II)

QF002/8/3

Figure 8.1 An Illustration of A Function flow

The declaration tells the compiler the name, return type, and parameters of the function.

Functions (Part II)

QF002/8/4

There are three ways to declare a function:


Write your prototype into a file and then use the #include directive to include it in your program. Write the prototype into the file in which your function is used. Define the function before it is called by any other function. When you do this, the definition acts as its own declaration.

 Function declaration is separated from its definition. A function declaration is simply the functions header, followed by a semicolon.  Function declaration is also called a function prototype.  Function declaration is like a variable declaration, its pu rpose is simply to provide the compiler with all the information it needs to compile the rest of the file.  Function definition is the complete function (header and body)  Figure 8.2 shows how to define the function

Functions (Part II)

QF002/8/5

function_type function_name(parameter List) { Variable declaration return expression } Figure 8.2 An Example Of Simple Statement Note:
Function_type is any valid C++ data type Function_name is any valid C++ identifier Parameter_list is a list of parameters separated by commas Variable declaration is a list of variables declared within the function return is a C++ keyword Expression is the value returned by the function

 The function_type indicates the type of value that the function will return when the return statement is executed.  The return value may be of any valid type: int,float,char.  Type void is used when the function does not return any value to the calling program(function).  The function_name is the name of the function and the parameter_list is a list of parameters separated by commas. The parameter type tells what value the parameter can receive when the function is called or invoked.

Functions (Part II)

QF002/8/6

 Parameter_list must include its name and t ype. The parameter_list declaration takes the form: type var_1,type var_2type var_n  when the parameter_list is empty or use either function_name() or function_name (void).

8.1 Function Scope

What is the scope in a program ?

The scope of an identifier is that part of the program where it can be used. For example variable cannot be used before they are declared, so their scopes begin where they are declared.

 Function scope is the scope of a name that consist part of the program where it can be used. It begins where the name is declared. If that declaration is inside a function (including the main() function), then the scope extends to the end of the innermost block that contains the declaration

Functions (Part II)

QF002/8/7

 Figure 8.3 shows the example of the application of the nested and parallel scopes in a program.
void f() void g() int x = 11; main () { Global scope Global variable Local scope

int x = 22; { int x = 33; cout << "In block inside main(): x= " << x<<endl; } cout << " In main() : x = " <<x<<endl; cout << " In main (): ::x =" << ::x<<endl; f(); g(); }

Figure 8.3: An example of simple program

Note:
f () and g () are global functions, and the first x is a global variable. So their scope includes the entire file. This is called file scope. The second x is declared inside main() so it has local scope.

Functions (Part II)

QF002/8/8

8.2 Local Variable

 A local variable is one that is declared inside a block. It is accessible only from within that block.  Figure 8.4 is an example of using parameters and locally defined variables within a function.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

#include <iostream.h> float Convert(float); int main() { float TempFer; float TempCel; cout << "Please enter the temperature in Fahrenheit: "; cin >> TempFer; TempCel = Convert(TempFer); cout << "\nHere's the temperature in Celsius: "; cout << TempCel << endl; return 0; } float Convert(float TempFer) { float TempCel; TempCel = ((TempFer - 32) * 5) / 9; return TempCel; }

Figure 8.4: An Example Of A Simple Program

Functions (Part II)

QF002/8/9

Note:
Execution jumps to the first line of the function Convert() where a local variable which is also named TempCel, is declared. Note that this local variable is not the same as the variable TempCel on line 6. This variable exists only within the function Convert(). The value passed as a parameter, TempFer, is also a local copy of the variable passed in by main(). This function could have named the parameter FerTemp and the local variable CelTemp and the program would work equally well. You can enter these names again and recompile the program to see this work.

Figure 8.5: An Example Of An Output Of A Program

Functions (Part II)

QF002/8/10

8.3 Global Variables

 Global variables are variables defined outside of any function. They have global scope and thus are available from any function in the program, including main ().  Global variable is not declared within a function. Any function defined after the declaration can access that variable as long as the function does not declare its own variable with that name.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

#include <iostream.h> void myFunction();

// prototype

int x = 5, y = 7; // global variables int main() { cout << "x from main: " << x << " \n"; cout << "y from main: " << y << " \n\n"; myFunction(); cout << "Back from myFunction!\n\n"; cout << "x from main: " << x << " \n"; cout << "y from main: " << y << " \n"; return 0; } void myFunction() { int y = 10; cout << "x from myFunction: " << x << " \n"; cout << "y from myFunction: " << y << " \n\n"; }

Figure 8.6: An Example Of A Simple Program Note:


The global variable x is initialized with the value 5 and the global variable y is initialized with the value 7. On lines 8 and 9 in the function main() , these values are printed to the screen. Note that the function main() defines neither variable; because they are global, they are already available to the main() .

Functions (Part II)

QF002/8/11

8.4 Making function call

 A function call is an expression that can be used as a single statement or within another statement.

Start Program Execution Flow

Function Call

Function Execution Function Return

End

Figure 8. 7: An Program Execution Jumps To An Invoked Function When A Function Call Is Made

Note:
When a function call is made, the program execution jumps to the function and finishes the task assigned to the function. Then the program execution resumes after the called function return.

Functions (Part II)

QF002/8/12

Activity 8a

Test your comprehension before continuing to the next input. Check your answers on the next page.

8.1. 8.2. 8.3. 8.4.

What are the three ways to declare a function?


Define the local variable ? Define the global variable ? Write a statement for the function declaration ?

Functions (Part II)

QF002/8/13

Feedback 8a

Make sure you have tried to answer a ll the questions given. You can check your answers with the answers below.

8.1. i. Write your prototype into a file and then use the #include directive to include it in your program..

ii.

Write the prototype into the file in which your function is used.

iii. Define the function before it is called by any other function. When you do this, the definition acts as its own declaration. 8.2. The parameters passed on to the function are also considered local variables and can be used exactly as if they had been defined within the body of the function.

8.3. Variables defined outside of any function have global scope and thus are available from any function in the program, including main(). 8.4. function_type function_name (parameter List) { Variable declaration return expression }

Functions (Part II)

QF002/8/14

INPUT

8.5 Argument Passing By Value

 Expression used in the function call is evaluated first and then the resulting value is assigned to the corresponding parameter in the function parameter list before the function begins executing.  For example:
num( y)
If y has value 9, then the value 9 is passed to the local variable y before the function begins to execute its statements.

 The value of y is used locally inside the function, the variable y is unaffected by the function. Thus the variable y is a read-only parameter  The pass-by-value mechanism allows for more general expression to be used in place of an actual pa rameter in the function call.  The read-only, pass-by-value method of communication is usually what we want for functions. It makes the function more self-contained, protecting against accidental side effects.

Functions (Part II)

QF002/8/15

 Figure 8.8 below shows a more detailed example of passing by Value


#include <iostream.h> void sum(int,int); void main ( ) { int x,y; //void name(int,int,int); cout <<"enter two numbers: \n" ; cin >>x>>y; sum(x,y); } void sum(int x, int y) { cout <<"\n Sum = x + y = "<< x+y; }

Figure 8.8: An Example Of Passing By Value

Figure 8.9: An Example Of An Output Of A Program

Functions (Part II)

QF002/8/16

8.6 Argument Passing By Reference

 In order to pass a parameter by reference instead of by value, simply append an ampersand & to the type specifies in the function parameter list. This makes the local variab le a reference to the actual parameter passed to it. ampersand (&)

void swap ( float& x , float& y )

 The parameter actually read -write instead of read-only. Then any change to the local variable inside the function will cause the same change to the actual parameter that was passed to it.  Figure 8.10 Shows the statement swap ( ) function
void swab( float& a, float& b) { float temp = a; a = b; b = temp; }

Figure 8.10: A Statement Swap ( ) Function

The reference operator & makes a and b synonyms for the actual parameters passed to the function

Functions (Part II)

QF002/8/17

 Figure 8.11 shows a more detailed example of passing by reference


#include <iostream.h> main ( ) { int x,y,sum; void name(int&,int&, int&); cout <<"enter two numbers: \n" ; cin >>x>>y; name(x,y,sum); cout <<"\n Sum = x + y = "<<sum; return 0; }

Figure 8.11: An Example Of A Passing By Reference

Figure 8.12: An Example Of An Output Of A Program

Functions (Part II)

QF002/8/18

8.7 Return (void)

 Functions return a value or return void. Void is a signal to the compiler that no value will be returned.  To return a value from a function, write the keyword return followed by the value you want to return. The value might itself be an expression that returns a value. For example:
return 3; return (y > 3); return (Function1());

Note:
These are all legal return statements, assuming that the function Function1( ) itself returns a value. The value in the second statement, return (y > 3), will be zero if y is not greater than 3 or it will be 1. What is returned from the function is the value of the expression that is 0 (false) or 1 (true) and not the value of x.

Functions (Part II)

QF002/8/19

 When the return keyword is encountered, the expressio n is returned as the value of the function. Program execution returns immediately to the calling function and any statements following the return are not executed.
8.8 Function prototype

 Function prototype specifies the name of the function, the number and type of arguments as well as the return value.  The prototype is used to check if the number of arguments and their types in the calling function correspond to the number of parameters and their types in the called function.  The general form of a function prototype declaration is shown in figure 8.13 below: type function_name (type parameter_1, type parameter_2 . .. type parameter_n); Figure 8.13: Declaration General Form Of A Function Prototype

 The example of a function prototype declaration is shown below:

void sum ( int x, int y, int z, float j, float k float m);

Figure 8.14: An Example Of A Function Prototype Declaration

Functions (Part II)

QF002/8/20

The example of program function prototype is shown below:


#include <iostream.h> void sum(float,float,float); void main ( ) { Function prototype float x,y,z; cout <<"enter three numbers: \n" ; cin >>x>>y>>z; sum(x,y,z); } void sum(float x, float y, float z) { cout <<"\n Sum = x + y + z = "<< x+y+z; }

Figure 8.15: An Example Of A Function Prototype Declaration

 The output of function prototype program is shown below:

Figure 8.16: An Output Of Function Prototype Program

Functions (Part II)

QF002/8/21

8.9 Function Overloading

 The C++ Programming allows you to use the same name for different functions but they must have different parameter type lists.  To be distinguished, the parameter list must either contain a different number of parameters or there must be at least one position in their parameter list where the types are different.

Can an overloaded function have a default parameter? Yes. There is no reason not to combine these powerful features. One or more of the overloaded functions can have their own default values, following the normal rules for default variables in any function.

Functions (Part II)

QF002/8/22

Activity 8b

Test your comprehension before continuing the next input. Check your answers on the next page.

8.5. 8.6. 8.7.

Describe the Argument Passing By Value Describe the Argument Passing By Reference Explain the statement bellow :

return 3; return (y > 3); return (Function1());

Functions (Part II)

QF002/8/23

Feedback 8b

Make sure you have tried to answer all the questions given. You can check your answers with the answers below.

8.5.

Expression used in the function call is evaluated first. Then the resulting value is assigned to the corresponding parameter in the functions parameter list before the function begins executing .

8.6.

To pass the parameter by reference instead of by value, simply append an ampersand & to the type specifies in the function parameter list. This makes the local variable a reference to the actual parameter passed to it.

8.7.

These are all legal return statements, assuming that the function Function() itself returns a value. The value in the second statement, return (y > 3), will be zero if x is not greater than 3, or it will be 1. What is returned is the value of the expression, 0 (false) or 1 (true), not the value of x.

Functions (Part II)

QF002/8/24

Key Facts

 A function is a subprogram that can act on data and return a value .  There are three ways to declare a function  A local variable is one that is declared inside a block. It is accessible only from within that block.

 Global variables are variables defined outside of any function. They have global scope and thus are available from any function in the program, including main ().

 The C++ Programming allows you to use the same name for different functions but they must have different parameter type lists.

Functions (Part II)

QF002/8/25

Self-Assessment

You are approaching success, please answer the questions below. If you have any problems, please discuss it with your lecturer. Wish you good luck and all the best.
Question 8 1

a. Why not all variables can be a global variable? b. If a function doesn't return a value, how do you declare the function? c. What is a local variable? d. What is a scope? e. What is a recursion? f. When should you use global variables?

Question

82

a. Write a simple program that uses of passing by Value b. Write a simple program that uses of passing by reference c. What is the output of the program below?
#include <iostream.h> void sum(float,float,float); void main ( ) { float x,y,z; cout <<"Enter 3 numbers: \n" ; cin >>z>>y>>x; sum(x,y,z); } void sum(float z, float y, floatxz) { cout <<"\n Sum = z + y - x = "<< x+y+z; }

Functions (Part II)

QF002/8/26

If the input is: i. x = 20 , y = 40 and z = 5 ii. x = 14 , y = 20 and z = 12 iii. x = 10.4 , y = 20.5 and z = 13.3 iv. x = 12.2 , y = 10.3 and z = 21.45 v. x = 3.2 , y = 2.4 and z = 1.3

d. Write the prototype for a function named Perimeter(), which returns an unsigned long int and that takes two parameters, both unsigned short ints. e. What is wrong with the function in the following code?

#include <iostream.h> void myFunc(unsigned short int x); int main() { unsigned short int x, y; y = myFunc(int); cout << "x: " << x << " y: " << y << "\n"; } void myFunc(unsigned short int x) { return (4*x); }

Functions (Part II)

QF002/8/27

f. What is wrong with the function in the following code? #include <iostream.h> int myFunc(unsigned short int x); int main() { unsigned short int x, y; y = myFunc(x); cout << "x: " << x << " y: " << y << "\n"; } int myFunc(unsigned short int x); { return (4*x);}

g. Write a function that takes two unsigned short integer arguments and returns the result of dividing the first by the second. Do not do the division if the second number is zero, but do return -1.

Functions (Part II)

QF002/8/28

Feedback On Self-Assessment

Make sure you have tried to answer all the questions given. You can check your answers with the answers below.

Answer 8 1

a.

There was a time when this was exactly how programming was done. As programs became more complex, however, it becames very difficult to find bugs in programs because data could be corrupted by any of the functions global data can be changed anywhere in the program. Years of experience have convinced programmers that data should be kept as local as possible and access to changing that data should be narrowly defined.

b. c.

Declare the function to return void. A local variable is a variable passed into or declared within a block, typically a function. It is visible only within the block.

d.

Scope refers to the visibility and lifetime of local and global variables. Scope is usually established by a set of braces.

e. f.

Recursion generally refers to the ability of a function to call itself. Global variables are typically used when many functions need access to the same data. Global variables are very rare in C++; once you know how to create static class variables, you will almost never create global variables.

Functions (Part II)

QF002/8/29

Answer 8 2

a.

#include <iostream.h> void sum(int,int); void main ( ) { int x,y; //void name(int,int,int); cout <<"enter two numbers: \n" ; cin >>x>>y;
sum(x,y); } void sum(int x, int y) { cout <<"\n Sum = x + y = "<< x+y; }

b.

#include <iostream.h> main ( ) { int x,y,sum; void name(int&,int&, int&); cout <<"enter two numbers: \n" ; cin >>x>>y; name(x,y,sum); cout <<"\n Sum = x + y = "<<sum; return 0; }

Functions (Part II)

QF002/8/30

c. i.

ii.

iii.

Functions (Part II)

QF002/8/31

iv.

v.

d. unsigned long int Perimeter(unsigned short int, unsigned short int); e. unsigned long int Perimeter(unsigned short int length, unsigned short int width) { return 2*length + 2*width; }

f. The function is declared to return void and it cannot r eturn a value.

Functions (Part II)

QF002/8/32

g. This function would be fine, but there is a semicolon at the end of the function definition's header.

short int Divider(unsigned short int valOne, unsigned short int valTwo)

{ if (valTwo == 0) return -1; else return valOne / valTwo; }

CONGRATULATION May success be with you always..

Das könnte Ihnen auch gefallen