Docsity

Functions Part 3-Introduction to Computer Programming-Lecture Slides, Slides of Computer Programming

Partial preview of the text

Download Functions Part 3-Introduction to Computer Programming-Lecture Slides and more Slides Computer Programming in PDF only on Docsity!

CS 192Lecture 15Winter 2003January 16, 2004Dr. Shafay Shamail

Passing Values

-^ Ways to pass an argument to a function–^ By Value^ –^ By Address^ –^ _By Reference____________________________________ •^ By Value^ #include <iostream.h>int sqr_it(int x);int main(){ int t=10;cout << sqr_it(t) << ' ' << t;

//output?

} int sqr_it(int x){^ x = x*x;return x;} • A copy of the^ value^ of argument^

t^ is passed to the formal parameter

x.^ t^ remains

unaltered.

(copy)t 10 10 x^10 docsity.com

Passing References

-^ By Reference^ –^ Eliminates the need to manipulate pointers or to remember to pass address ofargument. Not there in C^ #include <iostream.h>void sqr_it(int &x);int main(){ int t = 10;cout << "Old value for t: " << t << '\n';sqr_it(t); // pass address of t to sqr_it()cout << "New value for t: " << t << '\n';return 0;} void sqr_it(int &x){^ x *= x; // this modifies calling argument t} •^ Output:^1

References

-^ A reference is an

alias^ for the variable.

-^ Simply follow the parameter’s type by an ampersand in prototype e.g.^ int^ &x, pronounced “x is a reference to an int”•^ We passed the address of

t^ to^ sqr_it()^ by assigning another name to t, which was^ x. • Now the compiler automatically knows that whenever

x^ is encountered, we mean

t, because they are the same memory location

-^ To pass by reference, simply call the function with the variable namei.e.^ sqr_it(t) •^ Now mentioning the variable by its parameter name (new alias) in thefunction body accesses the original variable in the calling function

one variable,10 100 5FF two names t, x

Independent References• Output of following programme? #include <iostream.h>int main(){ int x = 3, &y;cout << "x = " << x << endl << "y = " << y << endl;y = 7;cout << "x = " << x << endl << "y = " << y << endl;return 0;} • error C2530: 'y' : references must be initialized • Output if we do int &y = x;^? • Not a good idea to use independent references as not necessary and inherentlyconfusing to have two names for same variable

References

-^ Output?^ #include^ <iostream.h>int^ main(){ int^ rats^ =^ 101;int^ &rodents^

=^ rats;cout << "rats =^ "^ <<^ rats;cout << ", rodents^ =^ "^ <<^ rodents

<<^ endl; rodents++;cout^ <<^ "rats^ =^ "^ <<

rats; cout^ <<^ ",^ rodents^

=^ "^ <<^ rodents^ <<^ endl; cout^ <<^ "rats'^ address

=^ "^ <<^ &rats; cout^ <<^ ",^ rodents'

address^ =^ "^ <<^ &rodents

<<^ endl; return 0;} • Output:^ rats^ =^ 101,

rodents^ =^101 rats = 102, rodents^ =^102 rats’ address^ =^ 006FD,^ rodents’

address^ =^ 0068FD

References

-^ A reference keeps referring to the same variable to which itwas initialized. You cannot change it by assignment later on •^ int^ rats^ =^ 101;int^ *pi^ =^ &rats;int^ &rodents^

=^ *pi;int bunnies = 50;pi = &bunnies;cout << *pi <<^ endl^ <<^ rodents

<<^ endl^ <<^ rats

<<

endl; • Output:^50

101

-^ Initializing^ rodents

to^ *pi^ makes it refer to

rats. Subsequently altering

pi^ to point to^ bunnies

does not alter the fact that^ rodents^

refers to^ rats

Returning References from Functions• The return type of function determines that a reference is passed• Can use such function on LHS of assignments! Can’t do so with ordinary functionsthat have the usual return types^ #include <iostream.h>double &f();double val = 100.0;int main(){ double newval;cout << f() << '\n'; // display val's valuenewval = f(); // assign value

of val to newval

cout << newval << '\n'; // display newval's valuef() = 99.1; // change val's valuecout << f() << '\n'; // display val's new valuereturn 0;} double &f(){ return val; // return reference to val} • Output: 100 100 99.

Returning References from Functions• If a function returns a reference to a variable local toitself, what happens?^ int &f(){ int i=10;return i;} • i goes out of scope when

f()^ returns. The behaviour of compilers is unpredictable in such cases. Somemight give warning, some might give error. So becareful!• One way to avoid is to return reference to a global, orto a variable that was passed to the function from thecalling function

When to Use Reference Arguments• We use them for two reasons:– To alter a data object in the calling function– To speed up a programme by not passing entire data object• Second reason important for large data objects,such as structures and class objects• When to pass by value, by pointer, byreference? Some guidelines:– If the data object is small, such as a built-in data type or asmall structure, pass it by value– If the data object is an array, no choice but to use a pointer– If large data object is a structure, use a reference or pointer– If large data object is a class object, use a reference

Function Overloading• C++ allows you to give two or more functions

the same name. The function is said to be

overloaded

-^ You can have a function

average()^ that computes average of integers, another

average()^ that calculates average of doubles• How can we do that without

ambiguity?

-^ Signature^ of a function is its list of parameters•^ Overloaded functions must have different signatures•^ Must differ in either the number, type, or order ofarguments i.e. different signatures•^ Compiler can differentiate then and calls the correctversion of the function

Function Overloading• Have you encountered overloading of some sort untilnow in C++ (not necessarily function overloading)?• The arithmetic operators. 2^ +^

3 and 2.2^ +^ 3.

-^ The^ +^ operator is overloaded•^ So, when to use overloaded functions?•^ When same sort of operation is to be performed ondifferent data sets•^ Advantage: Overloading functions that performclosely related tasks can make programs morereadable and understandable•^ Also called^ function polymorphism

Function Overloading• Write overloaded functions, one of which averagesthree double numbers, and the other two doubles • double ave(double^ n1,^ double

n2) { return((n

+^ n2)/2.0); } • double^ ave(double

n1,^ double^ n2,

double^ n3) { return^ (n

+^ n2^ +^ n3)/3.0); } • How about:^ int

ave(double^ n1,

double^ n2)...?

-^ Syntax error. Return type not considered by compilerwhile differentiating between functions

Exercise

Write three overloaded functions that take integer, double andlong respectively, and return their absolute values^ #include^ <iostream.h>int^ abs(int^ i);double^ abs(double^

doubled);long abs(long l); int main(){ cout << abs(-10) << "\n";cout << abs(-11.0) << "\n";cout << abs(-9L) << "\n";return 0;} int abs(int i){ cout << "using integer abs()\n";if(i<0) return -i;else return i;} abs(double^ d){ cout^ <<^ "using^ double^ abs()\n";if(d<0.0)^ return^ -d;else^ return^ d;} long abs(long^ l){ cout^ <<^ "using^ long^ abs()\n";if(l<0)^ return^ -l;else^ return^ l;}