Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading...

28
Computer Programming 1 More on functions
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    218
  • download

    1

Transcript of Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading...

Page 1: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming1

More on functions

Page 2: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming2

Objectives

Function overloading Scope rules and namespace Inline Templates Pass by value and pass by reference Recursion

Page 3: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming3

Scope

What is wrong with the following piece of code? int n; n++; double n; Although the two function have parameters with same name,

they compiler will not complain about re-declaring n twice! int sum (int n) {

return n * (n + 1) / 2; }int sum (int m, int n){

assert ( m < n) ;return (n – m + 1) * (n + m) / 2;

}

Page 4: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming4

Scope, scope rules

The scope of an identifier is the portion of the program where it can be accessed. The scope rules are:1. If an identifier is declared within a block, its scope runs

from that point to end of block2. If an identifier is a function parameter, its scope is the body

of the function3. If an identifier is declared in the initialization of a for loop,

its scope is to the end of the loop4. If an identifier's scope is declared outside all blocks and it

is not a parameter, then it scope runs from that point to the end of the file

Page 5: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming5

Namespaces

To be able to re-use declarations, namespace can be used Declarations can be placed within a namespace block

namespace belNS {

int value; //other declarations, definitions …

}

namespace mohNS {

int value;

} Elements within the namespace can be accessed

– By using the fully qualified namebelNS::value – mohNS::value

– By its unqualified name (if no conflict), value, if usingusing namespace belNS::value;orsing namespace belNS;

Page 6: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming6

Function Overloading

Can we have two functions with the same name and at the same time hold to the rule about no redeclaration of identifiers?

The function signatures were different– Different numbers of parameters– Different types of parameters

When this occurs we say the function name has been "overloaded"

int sum (int n);int sum (int m, int n);

int sum(double n);

Page 7: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming7

Inline Functions

When one function calls another void f( int n ){

... x = g(n); ...

}the process takes time for the program to transfer to a different location within the machine code

With inline, it is possible to avoid the overhead required by this transfer

Page 8: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming8

Inline Functions

Use the inline specifier in the prototype and definitioninline double fahrToCelsius (double temp); . . .inline double fahrToCelsius (double temp){

return (temp – 32.0)/1.8; } The compiler now places actual code for the function in each location it

is called– There is no jump to one location for the code at run time– This is very useful when a function with small code is called several times

Inline functions are a trade-off– Faster execution at run time … but … – Larger .exe file

Note that the compiler has the choice to inline a function or not Sometimes, a compiler may inline a function although the inline

keyword is used

Page 9: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming9

Pass by value and Pass by reference

So far, we have dealt with pass by value: only the value of the arguments are passed to the parameters

double x = 212.0; change (x);//what’s the value of x?

How can we change the value of x after change?– Changing a value parameter changes the copy not its

corresponding argument. Consider the task to divide two integers

– We compute both the quotient and the remainder– We desire a function which returns both values, but we can only

return value. What can we use to solve this?

void change (double t) {t = 10.0;

}

Page 10: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming10

Pass by reference

Reference parameters – Parameters declared with an ampersand (&) – Following the parameter’s type (and before its name).

A reference parameter is an alias to its corresponding argument.

– Acts like another name for actual parameter

Changing the value of a reference parameter changes the value of its corresponding argument.

Page 11: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming11

Pass by reference

Function stub with reference parameters:

void divideInts (int op1, int op2, int &quotient, int &remainder) {

… }

quotient and remainder are passed by reference. So, the values they have when divideInts returns are the values that the arguments will receive when its called.

int i = 10,j=3; int quot=0,rem=0; divideInts(i,j,quot,rem); //the values of q and r becomes 3 and 1

Page 12: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming12

Passing values to parameters

Value parameter– A distinct variable containing a copy of its argument

– In previous example, op1 and op2 are value parameters

Page 13: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming13

Pass by reference

Reference parameter– An alias of (alternate name for) the corresponding argument in

the call– Changes to value of reference parameter will change the value of

the corresponding argument in the call

1

2

Page 14: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming14

Pass by reference

When the parameters are large then it is wise to use references

Passing large arguments by valuing can be very expensive

– Copying the value of the argument is very expensive when it is large

– To avoid changing the value a parameter the use of the keyword const is very important

int length(const string& s){

return s.length();

}

Page 15: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming15

Function template

Consider the following swap functionvoid swap(char& first, char& second){

char temporary = first;first = second;second = temporary;

}

Suppose we want to swap ints, doubles, strings, etc.. Are we going to write this function for every type?

– This is were function templates come in!

Page 16: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming16

Function Templates

Templates provide a pattern for the compiler to generate functions for whatever type of parameters are used in the calltemplate <typename Type> void swap(Type &a, Type &b){

Type tmp = a;

a = b;

b = tmp;

}

Page 17: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming17

Recursion

Consider a function to calculate n-factorial– From mathematics

– It can be defined recursively as follows

1 if n is 0

1 2 ... if n > 0n

n

1 if n is 0

n (n-1)! if n > 0n

Page 18: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming18

Recursion

A recursive definition must have two parts1. A base/default case (s)

The value is specified for one or more values of the parameter(s)

2. An inductive/recursive stepThe value for the parameter is specified in terms of previously defined value(s) and/or parameters

1 if n is 0

n (n-1)! if n > 0n

Page 19: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming19

Recursion

To calculate 5! we go through the following steps:

Page 20: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming20

Recursion

Then we backtrack

Page 21: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming21

Recursive Function

The recursive factorial function

int factorial (int n){ assert (n >= 0); if (n == 0) return 1; else return n * factorial (n – 1);

}

Page 22: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming22

Execution of Recursive Function

Observe the sequence of recursive calls whenint number = factorial(4);

Successiverecursive

calls

Page 23: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming23

Execution of Recursive Function

When factorial(n - 1) eventually sends a 0 as the value parameter, the base case is executed

– No more recursive calls

. . .

Page 24: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming24

Execution of Recursive Function

Now the calculated values are returned

112266

2424

Page 25: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming25

Numerical Methods

Mathematical models used to solve practical problems Computer programs are used to manipulate such

equations– Called "numerical methods"

Examples– Curve fitting– Equation solving– Differential equations– Solving linear systems– Integration

Page 26: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming26

Numerical Methods Example

Approximating the area under a curve

Numerical methods approach– Divide region into strips, sum the areas– Trapezoidal method

( )b

a

Area f x dx

Page 27: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming27

Function pointers

Consider the problem described in the previous slide:– Compute the area under a function

– If the function is known in advance, then it is easy to do. But suppose we want our program to take any function, how should we proceed?

Use function pointers

( )b

a

Area f x dx

Page 28: Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Computer Programming28

Function pointers

Function pointers allow us to treat functions as if they are one of the basic types

typedef double (*Fx)(double);

double integral(double a, double b, Fx f) { double sum = 0.0,x; int n;

// Evaluate integral{a,b} f(x) dx for (n = 0; n <= 100; n++) {

x = (n/100.0)*(b-a) + a; sum += (*f)(x) * (b-a)/101.0; //you can f instead of (*f) } return sum; }

double square(double x){

return x*x;

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

integral(0.0,1.0,square);

integral(0.0,1.0,third);