39
09/22/2008 MET CS 563 - Fall 2008 4. Functions 1 4. Functions, Procedures, Methods – 4. Functions, Procedures, Methods – Encapsulating Behavior Encapsulating Behavior SW Engineering Goal: SW Engineering Goal: Create modules of code that can be reused, easily understood readability easily modified maintainability, easily extended/reduced scalability. 1 1 st st step: step: the function idea from math. Functions are also known as procedures - usually when more than one value computed; and methods when in the context of object oriented programming Terminology: In general functions express a rule/law of computation; in programming it is an algorithm, that sets forth the steps to be executed by the machine, i.e. the function is a unit/module for a certain behavior, or the

4. Functions, Procedures, Methods – Encapsulating Behavior

Embed Size (px)

DESCRIPTION

4. Functions, Procedures, Methods – Encapsulating Behavior. SW Engineering Goal: Create modules of code that can be reused, easily understood  readability easily modified  maintainability, easily extended/reduced  scalability. - PowerPoint PPT Presentation

Citation preview

Page 1: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

1

4. Functions, Procedures, Methods – Encapsulating Behavior4. Functions, Procedures, Methods – Encapsulating Behavior

SW Engineering Goal:SW Engineering Goal: Create modules of code that can be reused,

easily understood readability

easily modified maintainability,

easily extended/reduced scalability.

11stst step: step: the function idea from math. Functions are also known as

procedures - usually when more than one value computed; and

methods when in the context of object oriented programming

Terminology: In general functions express a rule/law of computation; in programming it is an algorithm, that sets forth the steps to be executed by the machine, i.e. the function is a unit/module for a certain behavior, or the function encapsulates behavior.

Page 2: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

2

Math FunctionsMath FunctionsMathematics f ( x ) = y

Example: sin ( x ) = y

sin ( 90°) = 1 f

Domain X Y Range

x = 90° 1 = y

x y

input output

f

function name

argumentfunction

value

Page 3: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

3

What do we need to know for defining and using a function?What do we need to know for defining and using a function?

Definition: Definition: <type > <identifier> ( <type> <identifier>, <type> <identifier>, …)

<function-body>

type of returned value

name of function

type of argument(s)

argument name(s)

Example:Example:

int max2( int x, int y )

{ if (x >= y) return x; else return y; }

function body

function header:contains all info for use

max2( )

x

y

max(x,y)

Page 4: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

4

Using/Calling/Invoking FunctionsUsing/Calling/Invoking FunctionsCalling Environment / ClientCalling Environment / Client

int max2(int x, int y){ if (x >= y) return x; else return y; }main(){ . . largest = max2 ( i , j ); . .

}

i

j

max2( )

max(i,j)

formal parameters/arguments (x,y) in definition

actual parameters/arguments (i,j) in invocation

Invocation / Server

x

y

messages between client and server

Page 5: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

5

Formal and Actual Parameters; Parameter PassingFormal and Actual Parameters; Parameter Passingformal parameter:formal parameter: parameter that appears in function definition

only as PLACEHOLDER.

NO computation is done.actual parameter:actual parameter: parameter that appears in function invocation

gives the input value computation is performed

parameter passing:parameter passing: when the function is called its arguments receive specific values (through the actual parameters) that are used to perform the computation in this particular invocation. This process is called parameter passing.

The semantics of argument passing is the same as initialization - argument types are checked and conversion made if needed.

Depending on how it is performed the results on the calling environment are different.

C++ has three different mechanisms for parameter passing – by value, by reference, and by pointer.

Page 6: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

6

//Example 4.1: Built-in functions of the Standard Math Library //Stroustrup, p.660)

//file: mathLib.cpp#include <iostream>#include <iomanip>#include <cmath> //must be included to provide access to math library

//<math.h> in older versions and Cusing namespace std;

int main(){

double x; //Square root cout << "double sqrt(double number) computes the " << "square root of number, e.g. " << setiosflags( ios::fixed | ios::showpoint ) << setprecision( 3 ) << "\n\tsqrt(" << 9.0 << ") = " << sqrt( 9.0 )//note: error if 9 instead of 9.0 in some compilers

<< "\n\tEnter number you want to know the square root of: ";

cin >> x; cout << "\tsqrt( " << x <<") = "<< sqrt(x)<<endl;

Header of the standard math library(available functions specified in Visual C++ Programmer's Guide)

double sqrt(double number) computes the square root of number, e.g. sqrt(9.000) = 3.000 Enter number you want to know the square root of: 121 sqrt( 121.000) = 11.000

Page 7: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

7

Example 4.1 : pow()

//Power cout << "\ndouble pow(double x, double y) computes " << "x raised to power y, e.g. " << setiosflags( ios::fixed | ios::showpoint ) << setprecision( 3 ) << "\n\tpow(" << 2 <<','<< 4 <<") = " << pow(2, 4 ) << "\n\tEnter two numbers x and y to compute x raised to power y is: "; double y; cin >> x >> y; cout << "\tpow( " << x <<','<< y <<") = "<< pow(x, y)<<endl;

double pow(double x, double y) computes x raised to power y, e.g. pow(2,4) = 16.000 Enter two numbers x and y to compute x raised to power y is: 2 10 pow( 2.000,10.000) = 1024.000

Page 8: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

8

Example 4.1 : sin()

//sin const double PI=3.14159; cout << "\ndouble sin(double x) with x in radians computes " << "sin(x), e.g. " << setiosflags( ios::fixed | ios::showpoint ) << setprecision( 3 ) << "\n\tsin(" << 0 <<") = " << sin(0.0) //note: error if 0 instead of 0.0 in some compilers

<< "\n\tsin(PI/6)=sin(" << PI/6 <<") = " << sin(PI/6) << "\n\tEnter angle in radians to compute sin(x): "; cin >> x ; cout << "\tsin( " << x <<") = "<< sin(x)<<endl;

double sin(double x) with x in radians computes sin(x), e.g. sin(0) = 0.000 sin(PI/6)=sin(0.524) = 0.500 Enter angle in radians to compute sin(x): 1.57 sin( 1.570) = 1.000

Page 9: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

9

Example 4.1 : tan()

//tancout << "\ndouble tan(double x) with x in radians computes "<< "tan(x), e.g. "

<< setiosflags( ios::fixed | ios::showpoint ) << setprecision( 3 ) << "\n\ttan(" << 0 <<") = " << tan(0.0) //note: error if 0 instead of 0.0 in some compilers

<< "\n\ttan(PI/2)=tan(" << PI/2 <<") = " << tan(PI/2) << "\n\tEnter angle in radians to compute tan(x): "; cin >> x ; cout << "\ttan( " << x <<") = "<< tan(x)<<endl;

return 0;}

double tan(double x) with x in radians computes tan(x), e.g. tan(0) = 0.000 tan(PI/2)=tan(1.571) = 753695.995 Enter angle in radians to compute tan(x): .7855 tan( 0.785) = 1.000

should be , but no warning!

Page 10: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

10

//Example 4.2: Range and Domain Errors//Example 4.2: Range and Domain Errors

//file: outBound.cpp…..

const double PI=3.14159;//tancout << "\ndouble tan(double x) - tan(x)\n";cout << "\ttan(PI/2)=tan(" << PI/2 <<") = " << tan(PI/2)<<endl;cout << "\ttan(PI/4)=tan(" << PI/4 <<") = " << tan(PI/4)<<endl;cout << "\ttan(-PI/4)=tan(" << -PI/4 <<") = " << tan(-PI/4)<<endl;cout << "\ttan(-PI/2)=tan(" << -PI/2 <<") = " << tan(PI/2)<<endl;

//Square root cout << "\ndouble sqrt(double x) - square root\n";cout << "\tsqrt(-1.0) = "<< sqrt(-1.0)<<endl;cout << "\tsqrt(-1.0) = "<< sqrt(-1.0)<<endl;

//log cout << "\ndouble log(double x) - natural logarithm\n";cout << "\tlog(0.0) = "<< log(0.0)<<endl;cout << "\tlog(-1.0) = "<< log(-1.0)<<endl;

double tan(double x) - tan(x) tan(PI/2)=tan(1.57079) = 753696 tan(PI/4)=tan(0.785397) = 0.999999 tan(-PI/4)=tan(-0.785397) = -0.999999 tan(-PI/2)=tan(-1.57079) = 753696

double sqrt(double x) - square rootsqrt(-1) = -1.#IND

double log(double x) - natural logarithm log(0) = -1.#INF log(-1) = -1.#IND

correctly warns on infinite or not defined values

error and no warning!

Moral: Check Documentation and Boundary Cases!!!

Page 11: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

11

// Example 4.3Example 4.3: User defined functions//Functions returning numerical values - perimeter

double perimeter(double length, double width)//Computes perimeter of rectangle//Receives:sides of rectangle length, width - two doubles //Returns: perimeter - double{ double p; //functions can have their own declarations

// in this case and overkill, however, see area function below p = 2*(length + width); return p;}

definition of perimeter( )

Page 12: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

12

// Example 4.3Example 4.3 : area, isSquare

double area(double length, double width)//Computes area of rectangle//Receives:sides of rectangle length, width - two doubles //Returns: area - double{ return length * width;}

definition of area( )

bool isSquare(double length, double width)//Tests whether a rectangle is a square//Receives:sides of rectangle length, width - two doubles //Returns: true(1) if rectangle is a square and false(0) otherwise{

if (length==width)return TRUE; //return 1;

else return FALSE; // return 0;

}

definition of isSquare( )

Page 13: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

13

// Example 4.3Example 4.3 : mainint main(){ double side1, side2; //sides of a rectangle cout << "Computing the perimeter and area of a rectangle"<<endl; cout << "Enter the two sides of the rectangle: \n"; cin >> side1 >> side2; cout << "The perimeter is " << perimeter(side1, side2) << endl; cout << "The area is " << area(side1, side2) << endl; if (isSquare(side1, side2)) cout << "The rectangle is a square"; else cout << "The rectangle is not a square" << endl; return 0;}

Computing the perimeter and area of a rectangleEnter the two sides of the rectangle:3 5The perimeter is 16The area is 15The rectangle is not a square

Page 14: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

14

Unconditional Jumps return and exit

return <argument>;terminates function that executes the return statement.Examples: in main return 0 terminates program indicating successful

execution; in a function return identifier terminates function and returns value of identifier.

exit <argument>;terminates program no matter what function executes the exit statement.Examples: A popular convention for arguments are the values 0 for

successful execution and 1 for abnormal ending. The arguments are returned to the operating system. To protect the programs from changes in convention, the standard library (stdlib.h, or cstdlib) provides two symbolic constants EXIT_SUCCESS and EXIT_FAILURE. Using the symbolic constants is safer and enhances readability too. (Do not forget to include the standard library when working with the literals!)

Page 15: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

15

Functions with No Return Value

Function Definition: Function Definition: <return-type > <identifier> ( <type> <identifier>, <type> <identifier>, …) <function-body>

Special Cases: Special Cases: a) No Return Value a) No Return Value void <identifier> ( <type> <identifier>, <type> <identifier>, …)

<function-body>

Example: Function with argument and no return valuevoid errorMessage(int flag){

if(flag)cout<<"Flag is true\n";

elsecout<<"Flag is false\n";

}

Page 16: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

16

Functions with Empty Parameter Lists

b)b) Empty Parameter ListsEmpty Parameter Lists or

<return-type > <identifier> ( void ) <function-body>

Example: no return value, no arguments

void message(){cout<<"Function with no arguments and no return value\n";

}

Example: return value, but no arguments int absValue(void){

int x;cin>>x;if(x>)

return x; else

return -x;}

<return-type > <identifier> ( ) <function-body>

Note that void can be omitted if function has no arguments, but must be present if no value is returned

Page 17: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

17

Solution in ANSI C and C++:Solution in ANSI C and C++: Provide the information needed for the formulating the function call and nothing more.

This is

<returned-type> <function-name> ( <argument-type>,…,<argument-type> );

e.g. int min2 ( int , int );

double sqrt ( double);

Function PrototypesFunction Prototypes

"BEFORE" means the function definition is • in same file after invocation • in another file• in a library

function function prototypeprototype

Problem: Problem: Allowing function calls "BEFORE"BEFORE" the function is defined without causing confusion?

Page 18: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

18

Header FilesHeader Files

• The prototypes of all functions in a library, e.g. the standard libraries, are collected in files, called header files. The programmer can also create his/her own header files.

• "Old style" header files have the .h extension, e.g. iostream.h, string.h, iomanip.h

• "New style" header files omit the .h extension, e.g. <algorithm>, <memory>

• Header files must be included in order to make the function prototype available, e.g.

• #include <memory>

• #include < iostream.h >

• #include " myHeader.h" " " for programmer defined headers

< > for standard libraries

Page 19: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

19

Default Argument ValuesGoal: Goal: Provide values for arguments if none are specified. The argument values specified by the user override the default values

Specification: Specification: Defaults are specified with the first occurrence of the function name, typically with the prototype//Figure 3.5: Default argument valuesint max ( int = 0, int = 0);

int main(){

cout << "The largest number is " << max() << endl;cout << "The largest number is " << max(1,2) << endl;cout << "The largest number is " << max(3) << endl;

return 0;}int max(int x, int y){

cout<<" x="<<x <<" y="<<y<<endl; if (x >= y)

return x; else

return y;}

x=0 y=0The largest number is 0 x=1 y=2The largest number is 2 x=3 y=0The largest number is 3

No argument values supplied; default values for arguments

Two argument values supplied; default values are overridden

One argument values supplied; overrides first default; it is not possible to override the second default without overriding the first

Page 20: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

20

Call by ValueCall by ValueThe function uses the values of the actual parameters but cannot change them OUTSIDE the function.

int main(){

int n = 8, p;int product ( int ); cout << "This program computes the\n"

<< "product of the numbers from 1 to n" << endl;cout << "Enter number n: ";cin >> n ;

p = product ( n ) ;cout << "The product of the numbers from 1 to "

<< n << " is "<< p << endl;

return 0;}

int product ( int n ){

int product = 1 ;for ( ; n > 0 ; --n )

product *= n ;return product ;

}

n remains unchanged in main()

This program computes the product of the numbers from 1 to nEnter number n: 3The product of the numbers from 1 to 3 is 6

n is decremented in product()

function prototype as declaration in main( )

Page 21: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

21

Call by Reference with ReferencesCall by Reference with References Goal:Goal: Allow the function to change the actual arguments in the calling environment A reference object is a synonym or alias of another object.They are declared by the type of which they are an alias, followed by &Reference objects must be initialized as they are only aliases, i.e. they do not define/declare a new object:

Call by Reference with References - ExampleCall by Reference with References - Example int i;int& iRef = i; // iRef is an alias of i

Definition:Definition:void swapWithRef(int& a, int& b) { int s; s=a; a=b;

b=s;}

Call:Call:swapWithRef(x, y);

Page 22: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

22

Nested Function CallsNested Function Calls

Example:Example: Finding the largest of four numbers

Functions: max2 ( )max2 ( ) returns largest of two numbers

x max(x , y)

y max2 ( )

max4 ( )max4 ( ) returns largest of four numbers

max2 ( )

max2 ( )

max2 ( )

xy

zw

max (x, y)

max (z, w)

max (x,y,z,w)

max4 ( )

Page 23: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

23

// Example 4.4Example 4.4 : Nested function calls - largest of four numbers//main

int max2(int, int);

int max4(int, int, int, int);

int main(){ int a, b, c, d; cout << "Computing the largest of four numbers"<<endl; cout << "Enter four integers: \n"; cin >> a >> b >> c >> d; cout << "The largest number is " << max4(a, b, c, d) << endl; return 0;}

Page 24: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

24

// Example 4.4Example 4.4 : Nested function calls - largest of four numbers//function definitionsint max2(int x, int y)//Computes largest of two int//Receives:two int//Returns: largest{ if (x >= y)

return x; else

return y;}

int max4(int w, int x,int y, int z)//Computes largest of four int//Receives:four int//Returns: largest{ return max2(max2(w,x), max2(y,z));}

Computing the largest of four numbersEnter four integers:3 1 78 333The largest number is 333

Page 25: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

25

Random Number Generation rand ( ) Random Number Generation rand ( ) and strand ( ) strand ( )

Example:Example: Rolling a six sided die - See D&D, Ch. 3.8, p.170Problems:Problems: a) How to generate random numbers? b) How to limit the random values to the ones needed by the application, e.g. 1 to 6 for the six sided die? •The function rand ( ) from the standard library <stdlib.h> produces an integer in [ 0 , RAND_MAX] at random, i.e. every integer between 0 and RAND_MAX has an equal chance to be chosen when rand ( ) is called. RAND_MAX is a symbolic constant defined in stdlib.h and RAND_MAX > = 32767 = maximum value for 2 bytes int

• The function rand( ) is a pseudo random generator, in that although it picks values at random, it repeats the random sequence every time the program is executed:

Use rand() for developing and debugging your program.

• After debugging, one can produce random sequences by randomizing with the function srand( <unsigned> ). Every time the program runs an unsigned (positive) integer, called the seed, is given to srand( ) which "seeds" the rand() function to produce every time a different sequence.

Page 26: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

26

• “heads and trails” i = rand % 2i = rand % 2

• 6 sided die 1 2 3 4 5 6

i = rand ( ) % 6 i = rand ( ) % 6 0 1 2 3 4 50 1 2 3 4 5

j = rand ( ) % 6 + 1j = rand ( ) % 6 + 1 1 2 3 4 5 61 2 3 4 5 6

ScalingScaling: transforming the range of rand ( )

Page 27: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

27

Scope and Storage Classes

When and how long does object exist in memory?

Where can an object be used, accessed, referenced?

Given by scope rules that follow the basic principle:

a) object scope is within program

unit

(and any other unit nested within it) in which object has been declared

b) in case of identical identifiers, the object in the inner block supercedes the object in the outer block

Given by storage class specifiers:

auto: exists while its scope unit is active.

register: auto + advises the compiler to use a register; may be ignored, e.g. not enough registers available.

static: exists while the program is running

extern: static + indicates object declared outside current unit

blockfunction

file

static

automatic

local

global

Page 28: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

28

Static Variables (staticVariable.cpp)void f(int a){

while(a--){static int n = 0; //initialize onceint x = 0; //initialized a times in each call of f()cout << "n is " << n++ << " , x is " << x++ << endl;

}}

int main(){ f(3);}

n is 0 , x is 0

n is 1 , x is 0

n is 2 , x is 0

Static variables provide a function with its very own memory without

introducing global variables that can be accessed/modified/corrupted by

other functions

Page 29: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

29

// Example 4.5Example 4.5: Scope and Storage: What does the following program print?

int f(int a)//adds counter b to argument a,then increments b {

cout << "\tEntering f() \n";static int b = 1;cout << "\tf: a="<<a<<" b="<<b<<endl;a += b++;cout << "\tf: a="<<a<<" b="<<b<<endl;cout << "\tLeaving f() \n";return a;

}int main(){

cout << "Entering main()\n"; int x=0, a=10;

cout.setf(ios::fixed|ios::right); //DD,Ch.11cout<<"main: x="<<x<<" a="<<a<<endl;

x = f(a);cout<<"main: x="<<x<<" a="<<a<<endl;

x = f(a);cout<<"main: x="<<x<<" a="<<a<<endl;

Entering main()main: x=0 a=10 Entering f() f: a=10 b=1 f: a=11 b=2

Leaving f()main: x=11 a=10 Entering f() f: a=10 b=2 f: a=12 b=3 Leaving f()main: x=12 a=10

b local static: remains in memory after f() exits; and is available for the next f() invocation; b is not recreated/reinitialized with each f() call

a keeps its value in main, although it changes in f()

Page 30: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

30

// Example 4.5Example 4.5: Scope and Storage: What does the following program print?

{ cout << "\tEntering block\n";int a=100;cout<<"\tblock: a= "<<a<<endl;cout<<"\tLeaving block\n";}

cout<<"main: x="<<x<<" a="<<a<<endl;cout<<"Leaving main()\n";

return 0;}

Entering block block: a = 100 Leaving block()main: a = 10Leaving main()

a keeps its value in main, although it changes in block

local variable a in block declared, supercedes local variable a from the outer block

Note:Note:• Local variables default to auto, therefore the auto specifier is routinely omitted• Global variables default to extern; need to be included when program resides in multiple files

Page 31: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

31

Recursion vs. Iteration

Recursive: Recursive: Function that calls itself

Example: Example: factorial(1)=1factorial(n) = n*factorial(n-1)

RecursiveRecursive implementation:

unsigned long factorial(int n) {if(n<=1)

return 1; else

return n*factorial(n-1);}

IterativeIterative implementation:

unsigned long factorial(int n) {unsigned long f=1;for(n; n >1;n--)

f=n*f;return f;

}

• More elegant and readable• More overhead as multiple function calls

• Substantially more efficient• Always preferred when readability not sacrificed too badly

Page 32: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

32

Inline Functions

Goal: Goal: Advise the compiler to incorporate the function code within the program, thus avoiding the overhead of a function call. This is especially handy for small functions.However the compiler may disregard the advice

Definition: Definition: inline <return-type > <identifier> ( <type> <identifier>, …) <function-body>

Example:

inline double area(double length, double width) {return legth*width };

Note: recursive inline functions are possible; a clever compiler can generate the constant 720 for factorial(6), while another generates 6*factorial(5), and yet another an un-inlined call factorial(6).

Page 33: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

33

Overloading FunctionsOverloading Functions

Main Idea: Main Idea: Use the same function name (function overload) or operator symbol (operator overload) to perform different computations, initializations or other actions.

Why would this be useful?Why would this be useful?Example 1: Overloading functionsA function area() computes the area of a rectangle, given its two sides. For the special case of a square, we want to compute the area using the "same" function and input just one side. Solution: define two functions having the same name, but different argument lists, so that

area(7, 3) returns 21whilearea(7) returns 49

Page 34: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

34

Function Overload ExampleFunction Overload Example

In general when the same identifier (function name) is used for several different function definitions the set of resulting functions is referred to as an overloaded function. For the area definition in Example 1 (fnctOverload.cpp)

float area(float a, float b){return a*b;

}

float area(float a){return a*a;

}

Computes area of rectangle Input: two sides of type floatReturns area of type float

Computes area of squareInput: side of type floatReturns area of type float

Page 35: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

35

Function Overload Example (continued)Function Overload Example (continued)int main(){

float side1, side2;

cout << "This program computes areas of rectangles and squares" << endl;cout << "\nEnter the first side of the rectangle:";cin >> side1;cout << "\nEnter the second side of the rectangle:";cin >> side2;cout << "\nThe area of the rectangle is " << area(side1, side2)<<endl; cout << "\nEnter the side of the square:";cin >> side1;cout << "\nThe area of the square is " << area(side1) << endl;return 0;

} This program computes areas of rectangles and squares Enter the first side of the rectangle: 7Enter the second side of the rectangle: 3The area of the rectangle is 21Enter the side of the square: 7The area of the square is 49

Page 36: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

36

How does overload work?How does overload work?

   The compiler decides which function definition to choose through argument matching - the process of comparing type and number of the actual and formal arguments according to the function signature that includes the function name and the list of the argument types, not including const and ‘&’ .

      Note: The different definitions of the overloaded function cannot differ only in the type of the returned value; they must differ in the type or/and number of arguments sent to them. (see functOverload_DONOT.cpp)

Page 37: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

37

Rules for Resolving Overloading

1. Exact Match

2. Match with Type Conversion

(see fnctOverload_Promotion.cpp fnctOverload_Defaults.cpp )

Page 38: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

38

Functions - Summary• Functions encapsulate behavior.

• Functions interact with the (calling) environment by messages: they receive the parameter values and reply by the returned value.

• The parameters in the definition of a functions do not perform any computation and are therefore called formal parameters; The parameters in the invocation of a functions do perform the computation and are therefore called actual parameters;

• Function prototypes contain only the information needed to interact/use a function and allow the compilation of a call before the function definition.

• Parameters are passed by value, i.e. copies of the parameter values are given to the function and any changes to these parameters within the functions remain local, with no effect whatsoever to the values of the parameters in the calling environment.

• Functions can be called from within other functions, a process referred to as nested function calls.

Page 39: 4. Functions, Procedures, Methods – Encapsulating Behavior

09/22/2008 MET CS 563 - Fall 2008 4. Functions

39

Summary (continued)• function parameters can be supplied with default values in the first

occurrence – either prototype or definition - of the function. This allows calling the function without arguments (the defaults provide values), or with fewer arguments than specified in the parameter list (values are assigned from left to right without skipping and argument).

• static variable local to the function provide are initialized only once with the 1st function call and are alive till the end of the program.

• inline advises compiler to incorporated function code in program thus bypassing the function calling mechanism, and speeding up execution. However, the compiler may disregard the advice.

• function overload allows to use the same function name for different calculations

• an overloaded function is a set of functions with the same name each of them defined separately; the definitions of the functions cannot differ only in the type of the returned value, they must differ in the type and or number of the arguments.