sahar mosleh california state university san marcospage build-in functions

75
Sahar Mosleh California State University San Marcos Page Build-in Functions

Upload: evangeline-lawson

Post on 21-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Build-in

Functions

Page 2: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Functions

- A method for allowing a program to be implemented in pieces

- A function is a block of code that performs some operations and (possibly) gives back a result

- Suppose you were doing something really basic - e. g. opening a file, calculating a square root

- Silly to write code for this over and over- Much easier to include it in a library of routines and re-

use it whenever you want

Page 3: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Functions

- This is what happens whenever you use a #include to make use of a library of routines (a header file)

- e.g. when you include fstream, you get access to a routine to open a file

- also other routines we haven’t used yet

- Someone has written a set of functions, that you can make use of when you include the appropriate header file

Page 4: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Built-In functions

- There are many of these built-in functions and correspondingly, many header files

- For example, say you want to calculate a square root. That’s in the math header file.

#include<cmath>

Page 5: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Built- In Functions

#include <cmath>#include <iostream>using namespace std;

int main () {

float num, answer;cout << “Enter a value: ”;cin >> num;answer = sqrt(num);cout << “The square root of ” << num

<< “ is ” << answer << endl; }

< See Example 1>

Page 6: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Built- In Functions

- sqrt is the name of the function

- num is the value we want to take the square root of

- Like this one, functions require specific information to perform their jobs

- Parameters

Page 7: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Supplying Arguments

answer = sqrt( 3.7);answer = sqrt(6+2);

-When we call a function, we supply specific values (arguments) for the parameters the function requires

- They are supplied in brackets when we call the function- more on these terms later

- Arguments can be specified directly (i.e. as literals), in variables or constants, or as the result of complex expressions

Page 8: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Supplying Arguments

answer = pow(3,7);

- If we have to supply several arguments, we separate them by commas

- pow (also in math header file) calculates its first argument raised to the power of its second (37).

- The order of the arguments is important – if we reversed them, we’d get 73 !

Page 9: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Calling Built- In Functions

- What happens when we call a built-in function?

- The arguments we supply are evaluated, and passed to the function

- The function runs (code we don’t see - from the header file)

- The function eventually completes

- Often it calculates and returns a result

Page 10: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Returning a Result

- When a function returns a result, it will have a specific type– e.g: both pow and sqrt return floats

- We have to do something with this result– Store it:

answer = sqrt(X);– Print it:

cout << sqrt(X);– Pass it on to other calculations:

x = 2 + pow(7,14); y = sqrt( pow(2,4));

Page 11: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Output Formatting Functions- In the iomanip header file

- Allow us to create more nicely formatted output

#include <iostream>#include <iomanip>using namespace std;int main () {

int x = 4;cout << setw(5) << x << endl;

}

- setw sets the width (# spaces) the next data item should take up!

< see: Example 2>

Page 12: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Output Formatting Functions

cout << setw( 5) << x;

- Pads with blanks on left to appropriate length. Here, bbbb4 would be printed (where b = blank)

- Only works for the next item (i.e. you have to repeat this if you want the same formatting)

- Default for setw is 0 - leaves just enough room for value

- What about real numbers (floats)?

Page 13: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Formatting Floats

- The way in which floats are formatted depends on your compiler- The text gives a few lines that sets up floating point

formatting for whatever you’re using

cout.setf(ios::fixed, ios::floatfield);cout.setf( ios::showpoint);

- once you’ve done this (just copy in the lines, don’t even worry what they do) you can set the decimal point precision

Page 14: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Formatting Floats• setprecision( ) sets the number of decimal places to print

#include <iostream>#include <iomanip>using namespace std;int main () {

cout.setf(ios::fixed, ios::floatfield);cout.setf( ios::showpoint);cout << setprecision(3);float x = 4.7589;cout << setw(7) << x;

}

• Output: bb4.759 (where b= blank)

< See: Example 3>

Page 15: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Output Formatting Function

- Note the rounding - the number is rounded off for printing- doesn’t change the value in the variable at all

- The width will be increased if necessary to fit the number

- Unlike setw, setprecision has lasting effects- once used, all floats will continue to be printed that way

until you change it

Page 16: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

User- Defined Functions

- So, we know how to use functions provided for us by other programmers

- There are lots of them, but they obviously don’t cover everything we want

- We want to be able to write our own functions!

Page 17: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

User Defined Functions

- Why??- So we can re-use them later if we want- So we can divide our programs into pieces

- Re-use has obvious advantages – more compact programs, no repeated code, and not having to rewrite code later for similar problems

- But why would we want to divide a program into pieces?

Page 18: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Dividing Programs into Pieces

- To make the program more manageable- If we have pieces of a program that do individual tasks, we

can isolate errors and modifications

- Take the square root routine for example… if you had to write it…

- You could test it separately from the rest of your program; errors found later are not as likely to be in the square root function!

- You could modify the internals of the function without affecting the rest of your program!

Page 19: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Dividing Programs into Pieces

- Before we talk about how to create our own functions, we need to talk about dividing programs up

- Obviously, we don’t just do it randomly

Page 20: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Top-Down Design

- A technique for designing programs

- Useful without even knowing anything about functions

- Helps us to handle the “where do I start?”

- Lets us gradually design a program without being overwhelmed by details

Page 21: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Top-Down Design

- Begin with a high-level statement of the problem

- Clearly this is not something that you could implement directly - but it does give you a general statement of what you’re trying to do

- Now break this into smaller problems

Page 22: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Top-Down Design

- Asking the user is pretty much implementable at this point (a concrete step)

- Change prices is still pretty vague (abstract step), so we can break that one down too...

Update prices for big sale

Ask user for % off Change prices Change prices

Page 23: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

- Now everything is concrete - we’re done!

- Each box is a module, The entire diagram is a structure chart and shows how modules are related

- Each module should be functionally cohesive

- it should do one, well-defined thing

Change prices

Open price files Read a price Discount price Print new price

Top-Down Design

Page 24: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Top-Down Design

- You should always do a design for each program

- Gives you a handle on where to start- Ensures you know what you’re doing before you start

programming!

- You should only start implementing after your design is complete!

Page 25: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

User-Defined

Functions

The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

Page 26: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

User- Defined Functions

- Functions are a facility provided by C++ to implement the modules in your design

- Allows each module to be physically separate from others and re-used as necessary

- We’ve already been using user-defined functions. Every C++ program starts with one function called main(); we add others as necessary

Page 27: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

User- Defined Functions

- Are similar to built-in functions

- They have a name, parameters, can return a result, and are called exactly like built in functions

- So we know a lot about them already!

- Let’s look at a simple example

Page 28: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Simple Function Example

void printabar() { cout << “*****************************”; }

- The function header contains information like the name, what data it needs to do its job, etc. More on this in a moment

Function Header -Information aboutthe function

Function Body -statements that performthe function’s task

Page 29: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Simple Function Example

void printabar() { cout << “*****************************”; }

- Notice how similar this is to the programs we’ve been writing so far?

- That’s because main() is a function!- All C++ programs have a function called main, and that is where execution of the program begins

Page 30: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Simple Function Example

void printabar(){cout << “*****************************”;}

- How do we make use of this function?

- We call it, just like a built-in function- use it’s name and brackets: printabar();

Page 31: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Simple Function Example

void printabar(){

cout << “*****************************”;}

- We know what one looks like, we know how to call it, but where do we put them?- We already have one function in our program - main()

- We can put them in any order, but main() usually comes first

- so we can get an immediate overview of what the program does before looking at the details

- There’s a problem with this though…..

Page 32: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Declaration Before Use

- Many languages, including both C++ and Pascal, have a rule that forces you to declare anything you want to use before you use it

- That’s why we have to declare variables!

- This is a problem in functions. Suppose I want to call my printabar function inside main. If main comes first, how will the compiler know what I’m talking about!?!

Page 33: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

We could put printabar (and other functions we want to use) first; then, however, we’d have to hunt through all these details before we got down to main and found out what the program actually does!

We try to use printabar here

But because its down here, thecompiler hasn’t even seen it yetwe will get an error every timewe use it

void main (){

printabar(); }//---------------------------void printabar() {

}

Declaration Before Use

Page 34: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Prototypes

- There is a solution to this problem - a special statement that lets the compiler know what upcoming functions are going to look like before actually implementing them

- A Prototype

- Since most of the information about a function is in its header, it will look pretty much like the function header itself

- There will be a few differences we will see later when we look at more complicated functions

- Lets look at the whole thing using a prototype

Page 35: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Prototypes Example

#include <iostream>using namespace std;void printabar ();

void main () { // this is the main program pretend there’s // lots of other statements here

printabar();} // end main

//--------------------------------------------void printabar() { // printbar code goes here

} // end printbar

This prototype tells C++everything it needs to figureout if you are calling printabarproperly or not

Page 36: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Prototypes Example

#include <iostream>using namespace std;void printabar ();

void main () { // this is the main program // pretend there’s lots of other statements here

printabar();} // end main

void printabar() { // printabar code goes here // pretend there’s some statements here

} // end printabar

All the functions we use cannow immediately follow main,provided each has a prototypethat appears before main

Page 37: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

More Complex Functions

- We now know a fair bit about functions:- What one looks like- Where they appear in the program- how to call them

- But our functions don’t do much yet. Lets look at some more complex situations

Page 38: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Parameters

- Our printabar function is so trivial, it doesn’t really do much of anything

- Like most built-in functions, our own functions will generally require some information to work with

- Say we wanted to use printabar to print bars for a line graph -bars aren’t always the same length

- When we wanted to use the function, we’d have to provide some data indicating the number of characters to print

Page 39: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Parameters

- We indicate in our function that data will be provided when we call the function by declaring parameters

- A parameter acts like a variable (details later), and holds the value we give to the function when we call it

- You will also see Parameters called Formal Parameters - because they’re defined formally as part of the function

Page 40: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Using Parameters

void printabar (int numchars) {int count= 1;while (count <= numchars)

{ // loop to print 1 char at a time

cout << ‘*’;count++; //incrementing the counter

}cout << endl; }

- Here’s our function with a parameter added- We define its type and give it a name- We can have a list of parameters separated by commas (like declaring a bunch of variables)

Page 41: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Using Parameters

void printabar (int numchars) {

int count= 1;while (count <= numchars)

{ // loop to print 1 char @ a timecout << ‘* ’;count++; // remember to increment counter!

} cout << endl;

}

- Note that we don’t give the parameter a value!!! The value will be supplied when we call the function

Page 42: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Arguments

void main () {

printabar(6); printabar(3);

}

- Now we need to specify a value between the brackets when we call printabar

- This is an argument - data we supply to work with at the time we call the function- Arguments are also called Actual Parameters

- Arguments are matched to parameters by ORDER (we’ll talk about it later)

Page 43: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Parameters and Prototypes

void printabar(int);

- Here you see the appropriate prototype for the function with parameters

- Note its now a little different from the function header

- Prototypes give C++ the info it needs to tell if you are correctly calling the function

- It needs the name, needs to know if there are parameters and what type they are, but doesn’t care about their names- The names are optional; you only really need to list the types of the parameters in order

<See: Example 1>

Page 44: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Call by Value

Call by Reference

Page 45: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Returning Values

- The examples we’ve seen so far are very different from most built-in functions we’ve used

- They just do something - they don’t give any answer back!

- Most built- in functions calculate something and return it (sqrt, pow, etc.)

- How can we do this?

Page 46: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Void and Non-Void Functions

- Every function has a type- Part of the header, tells C++ what type of value the function will give back when we call it- The first word of the header defines the type of the function

- The functions we’ve used so far don’t return values- The type void is used to indicate this

- If you want to return a value, simply supply the type you want instead of void

Page 47: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Non- Void Functions

int mypower (int x, int y) { // raise x to power y (y >= 0) using a count- controlled loop

int count= 1; // loop counter

int answer= 1; // holds the answer

while (count <= y) { // loop to print 1 char @ a time

answer = answer * x; count++; } // end while

return answer; } // send answer back to caller

Note >1 parameter

Causes function to terminate and send back value we’ve specified

Page 48: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Calling Non-Void Functions

- When we call this function, just like most built-in functions, we need to do something with the result:

- Store it: answer = mypower(x,y);

- Print it: cout << mypower(2,3);

- Pass it on to other calculations:x = 2 + mypower(7,14);y= sqrt( mypower(2,4));

- Remember that the order of arguments matters!!!

Page 49: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Prototypes for Non-Void Functions

- For a prototype of this function, we need to add the type information (just as we needed to use void in earlier examples)

int mypower( int x, int y);

- Remember that you can actually put the parameter names if you want, but they’re irrelevant

Page 50: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

More on Return

- Return may also be useful in terminating a function prematurely

- You can use it anywhere in the function, and you can use it without a value in a void function to simply cause the function to terminate early- Example:

while (1) {

cin >> x; if (x < 0)

return; else

// lots of other code

}

Page 51: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

More on Return

- Is also commonly used in the main function- we usually give the main function a type of int, and return some integer indicating whether the program ran correctly- e. g. return 0 for no error, higher numbers for more severe problems

int main () {

// whatever main does

return 0;}

- The text uses this; feel free to use it if you want

Page 52: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

So far…

- We have functions which implement the modules in our program designs

- These functions can accept arguments, which provide data for the function to work with

- These functions can also return results if we want them to

Page 53: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Returning more than one result

- But suppose we want to return more than one result?

- Suppose you wanted an interactive program that would calculate volume for the user.

- You repeatedly want to obtain length, width, and height- This might be something you want a separate function for

- But how? A function can only return one result... but there are ways around this

Page 54: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Parameter Types

- The answer lies in a new type of parameter we haven’t seen yet

- Recall that the parameters we have used so far act like variables:

- They get created when a function is called- A value is passed into them from the caller- They cease to exist when the function returns

- So given that, what do you think would happen in the following example:

Page 55: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Example

int strange( int);

int main() { int arg = 7; cout << strange(arg); cout << endl << arg ;}

int strange( int y) { y = 6; return 0; }< See Example 4 >

We print the result ofcalling strange, which is 0(the value returned by strange)

But what’s happening here?We print arg, which is 7

Or is it? When we call strange, we change it’s parameter to 6….

Page 56: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Altering Parameter Values

- According to what we know happens with parameters, 7 should be printed

- That’s because -- the parameter y is created when the function runs- the argument is copied into it (the 7)...- and even though we change y to 6, y itself is destroyed when the function returns

- So our original argument, arg (with the value 7) is never touched and can’t be!

Page 57: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Parameter Types

- But it doesn’t always have to be this way!

- We are making use of only one of two types of parameters allowed by C++

- These are called Value Parameters, because as the name implies, the argument values are copied into the parameter, and the original argument can never be changed

- There’s a second type that DOES allow argument values to be changed

Page 58: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Reference Parameters

- This second type is called a Reference Parameter

- For the moment, just assume that when you declare one, you’re allowed to actually make changes to the argument being passed

- We can and do use this to return values from functions

- Since we can have as many parameters as we want, we can return as many values as we’d like in them by altering the parameters!

Page 59: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Reference Parameters

- Very easy to declare - just put an ampersand (&) at the end of the data type of the parameter name: int& x

- So, when writing functions, just ask yourself if you want the original argument to be changeable, and if you do, add the ampersand!

- Let’s see our strange example with reference parameters...

Page 60: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Example

int strange( int&);

int main() {

int arg = 7;cout << strange(arg);cout << endl << arg ;

}

int strange( int& y) {

y = 6;return 0;

}< See: Example 5 >

The parameter y is now aReference Parameter - thismeans that whatever we passto y can be altered!

Page 61: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Example

int strange( int&);

int main() {

int arg = 7;cout << strange(arg);cout << endl << arg ;

}

int strange(int& y) {

y = 6;return 0;

}

y will be set to the value 6...

So arg is passed to strange

y will be 7 as before

Page 62: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Example

int strange( int&);int main() {

int arg = 7;cout << strange( arg);cout << endl << arg ;

}

int strange( int& y) {

y = 6;int answer = y*2;return answer;

}- Obviously, we have to be careful with these!

arg, after the call tostrange, will also have thevalue 6!

Page 63: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Mechanics of Reference Parameters

- It’s important to understand what’s going on here

- First of all, reference parameters don’t behave any differently than value parameters

- They’re still created when the function is called- They still get an argument from outside- They’re still destroyed when the function returns

Page 64: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Mechanics of Reference Parameters

- Then how can they work the way they do?

- Do they copy the parameter back into the argument when the function returns?

- No, they don’t do that either

- Their behavior has everything to do with WHAT is actually being passed

Page 65: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Mechanics of Reference Parameters

- In a value parameter, the actual value of the argument is copied into the parameter

- The 7 is copied over and then strange runs

….….

arg

y 7

7

Page 66: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Mechanics of Reference Parameters

- In a reference parameter, the value is not passed; the memory address of the argument is!

- In fact, ‘y’ becomes an alias name for variable ‘arg’. Any change in ‘y’ makes the same change in ‘arg’

….….

argy

7

Page 67: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Back to our Example

- More importantly , considering the full example:

int strange( int& );int main() {

int arg = 7;cout << strange( arg);cout << endl << arg ;

}

int strange( int& y) {y = 6;return 0;

}

So when strange returns,arg has the value 6, and that iswhat is printed!

Page 68: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Something to Remember

- You never have to worry about the address business yourself!

- You don’t care in this example what the address of arg happens to be; the compiler handles all this for you

- This is an example of what’s properly called a pointer, something we’ll study in advanced C++ course

Page 69: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Returning Multiple Values

- We can use reference parameters to return as many values as we want

- In our original example, we wanted to read in length, width and height

- It’s easy now!

Page 70: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Returning Multiple Valuesint main() {

float l, w, h;getvalues(l, w, h); cout << “volume is “ << l*w*h;

}

//------------------------------------------------void getvalues(float& len, float& wid, float& height) {

cout << “enter an integer length: ”;cin >> len;cout << “enter an integer width: ”;cin >> wid;cout << “enter an integer height: ”;cin >> height;

}

Page 71: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Returning Multiple Values

- getvalues doesn’t return anything...

- instead, it has three reference parameters

- when we input values, we change these, and change the variables the caller supplies!

- Getvalues takes l, w, h as arguments, and because each of its parameters is a reference parameter, it actually modifies l, w, and h, effectively allowing the function to give back three values

< See: Example 6>

Page 72: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Returning Multiple Values

- But suppose I did this!

int main() {

int l, w, h;getvalues( 6, 2, 3);// other code after this

}

- It doesn’t make sense does it? How can the function change a 6, or a 2??? It can only change what’s stored in a variable!

Page 73: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Big Restriction

- We can only pass variables to reference parameters!

- As in the last example, this should make sense, because they’re the only things that can be modified

- i.e. the only things that have an address that can be referred to

- There’s one other thing to be aware of

Page 74: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Watch out for Type Coercion!

- We’ve seen that C++ tries to convert types to allow the statements we make

- e. g. converting characters to integers using the collating sequence if we assign a character to an integer

- Odd things happen if we do this in a reference parameter- since the types don’t match, it can’t use them directly- instead, it creates a second variable, coerces, and uses that

- Unexpected result can happen - so make the types to be the same when using call by reference

Page 75: Sahar Mosleh California State University San MarcosPage Build-in Functions

Sahar Mosleh California State University San Marcos Page

Use Reference Parameters Carefully!

- It’s easy to make changes to arguments you don’t intend

- Such changes can be hard to trace back!

- Don’t use reference parameters unless you want values passed back

- There are always exceptions, but treat this as a rule for now!