1 of 30

FUNCTIONS & DATA

A LECTURE FOR THE C++ COURSE

Each slide may have its own narration in an audio file. �For the explanation of any slide, click on the audio icon to start the narration.

The Professor‘s C++Course by Linda W. Friedman is licensed under a �Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

2 of 30

INTRODUCTION TO FUNCTIONS AND DATA

  • We need to protect data that is worked on in our functions.
  • There are many situations in which other users may have access to the data operated on within our functions.
  • We want to protect this data from change by others – or, at least we wish to know about it when it happens.

FUNCTIONS & DATA

2

3 of 30

WHAT CAN WE DO TO PROTECT DATA?

In this lecture we will learn about :

  • Scope
  • Lifetime
  • Storage class
  • Parameter passing

FUNCTIONS & DATA

3

4 of 30

FUNCTIONS AND DATA

When writing a program in modules – functions – there are several ways in which we deal with data, depending on our needs. Some issues:

      • Data may be required by the function, an input value much like f(x) in math.
      • The function may compute a value that must be returned back to the point of call, again, much like a mathematical function, y=f(x).
      • The function may have more than one data value to return to the point of call – or none at all.
      • The function may only use certain data items locally.
      • The function may be required to change the values of data used elsewhere in the program.

FUNCTIONS & DATA

4

5 of 30

GLOBAL AND LOCAL VARIABLES

Global variables – a.k.a. external variables – are accessible throughout all the functions in the program.

Local variables – a.k.a. automatic variables – are accessible only within the function (or other program module) in which they are declared.

#include <iostream>

using namespace std;

void func(); //function prototype

int x=27, y=10; //global variables

int main(){

cout << "\nIn function main, " << endl;

cout << "X= " << x << " and Y= " << y << endl;

func();

cout << "\nIn function main, again..." << endl;

cout << "X= " << x << " and Y= " << y << endl;

return 0;

}

void func(){ //function implementation

int y = 1042; //local variable

cout << "\nIn function func, " << endl;

cout << "X= " << x << " and Y= " << y << endl;

}

FUNCTIONS & DATA

5

6 of 30

SIDE EFFECTS

A side effect is an unintended change to a global variable from within a function.

#include <iostream>

using namespace std;

void SideEffects();

int x;

int main(){

x=10;

cout << "X= " << x << endl;

SideEffects(); // not clear here why the function call might

//change the value of x

cout << "X= " << x << endl;

return 0;

}

void SideEffects(){

x = 200;

}

FUNCTIONS & DATA

6

7 of 30

SCOPE

Every name (identifier) in a C++ program must refer to a unique entity. This does not mean that a name can be used only once. Sometimes, context is important.

Scope refers to the area of the program code where a declared variable (or object or function or …) is accessible, i.e., where it can be referenced. Depending on its scope, a variable may exist (lifetime) but still not be visible.

    • Local scope – local to function, block of code (compound statement)
    • Namespace scope; class scope [Later]

The lifetime of a variable is the duration of time during which it takes up space in memory, i.e., it exists.

FUNCTIONS & DATA

7

8 of 30

SCOPE

Example:

#include <iostream>

using namespace std;

 

int main(){

int x=10;

cout << x << endl << endl;

{

int x=25;

cout << x << endl << endl;

}

cout << x << endl << endl;

return 0;

}

FUNCTIONS & DATA

8

9 of 30

STATIC VARIABLES

A static variable looks like a local variable but it does not “die” when the function returns and retains its value for the next time the function is called. It is only accessible when the function is executing.

#include <iostream>

using namespace std;

//This program prints a ‘running’ average

double average (double x){

static double count = 0;

static double sum = 0;

 

count++;

sum += x;

return sum / count;

}

int main(){

cout << "average = " << average(1) << endl;

cout << "average = " << average(2) << endl;

cout << "average = " << average(6) << endl;

cout << "average = " << average(11) << endl;

cout << "average = " << average(5) << endl;

cout << endl << endl;

return 0;

}

FUNCTIONS & DATA

9

10 of 30

STATIC VARIABLES AND STORAGE CLASSES

Static is a storage class.

Other storage classes are

    • extern, for external – or global – variables
    • auto, for automatic – or local – variables

FUNCTIONS & DATA

10

11 of 30

PARAMETER PASSING

We know that when we call a function, we can pass data to it in the parameter list.

      • An actual parameter, or argument, is the data item that is passed from the calling function to the called function.
      • A formal parameter, or parameter, is the variable in the parameter list in the function implementation.

So far, our examples have used the default parameter passing mechanism, pass by value. The value of the argument is copied into the corresponding parameter; it is similar to a local variable in the executing function.

FUNCTIONS & DATA

11

12 of 30

PARAMETER PASSING

Suppose we wish to write a function that will swap two numeric values. It might look something like this:

void swap (float x, float y){

float temp = x;

x = y;

y = temp;

}

How does this work? Let's see (it doesn't). Here's a program to test this swap function:

#include <iostream>

using namespace std;

void swap (float, float);

int main(){

float a = 10;

float b = 27;

cout << "A= " << a << endl

<<"B= " << b << endl;

swap(a,b);

cout << "After swapping..." << endl

<< "A= " << a << endl

<<"B= " << b << endl;

return 0;

}

FUNCTIONS & DATA

12

13 of 30

PARAMETER PASSING

Why didn't the swap take place? After all, the function looks like it should work, but it doesn't work properly.

 

x and y, the formal parameters of swap are considered local to swap. Only the values of a and b (10 and 27) are passed to the swap function. Any changes that take place inside the function, stay there and do not get sent back to the actual parameters in the calling function. This is to protect our variables from unintentional modification. And is usually the best way to pass actual parameters (arguments) to formal parameters. Clearly, this doesn't work in all cases!

For the swap function to work as intended, we need to pass a reference to the location of the actual parameter so that it can be modified by the function. This is called passing by reference.

FUNCTIONS & DATA

13

14 of 30

PARAMETER PASSING

Trying again with reference parameters:

#include <iostream>

using namespace std;

void swap (float&, float&);

int main(){

float a = 10;

float b = 27.3;

cout << "A= " << a << endl

<<"B= " << b << endl;

swap(a,b);

cout << "After swapping..." << endl

<< "A= " << a << endl

<<"B= " << b << endl;

return 0;

}

void swap (float &x, float &y){

float temp = x;

x = y;

y = temp;

}

FUNCTIONS & DATA

14

15 of 30

PARAMETER PASSING

Exercise – what will output?

#include <iostream>

using namespace std;

void testing(int, int&);

int main(){

int a = 22, b = 33;

cout << "A= " << a << endl

<<"B= " << b << endl << endl;

testing(a,b);

cout << "A= " << a << endl

<<"B= " << b << endl;

return 0;

}

void testing (int x, int &y) {

x = 88; y = 99;

}

FUNCTIONS & DATA

15

16 of 30

PARAMETER PASSING

Exercise – what will output?

//from Hubbard book

#include <iostream>

using namespace std;

void testing(int, int&);

int main(){

int a = 22, b = 33;

cout << "A= " << a << endl

<<"B= " << b << endl << endl;

testing(a,b);

cout << "A= " << a << endl

<<"B= " << b << endl;

return 0;

}

void testing (int x, int &y) {

x = 88; y = 99;

}

FUNCTIONS & DATA

16

17 of 30

PARAMETER PASSING

Play computer – Exercise #1:

#include <iostream>

void fun (int, int, int);

int main(){

int a, b, c;

a = 27; b = 10; c = 3;

fun (a, 9, b+c);

cout << a;

return 0;

}

fun (int x, int y, int z){

x = x + y + z;

}

FUNCTIONS & DATA

17

Passing by value (the default)

18 of 30

PARAMETER PASSING

Play computer – Exercise #2. Here we are passing by value.

FUNCTIONS & DATA

18

19 of 30

PARAMETER PASSING

Play computer – Exercise #2:

#include <iostream>

using namespace std;

void fun (int&, int&, int&);

int main(){

int a, b, c;

a = 27; b = 10; c = 3;

fun (a, 9, b+c);

cout << a;

return 0;

}

void fun (int &x, int &y, int &z){

x = x + y + z;

}

FUNCTIONS & DATA

19

20 of 30

PARAMETER PASSING

Play computer – Exercise #2. Here we are passing by reference. What will actually happen here?

FUNCTIONS & DATA

20

21 of 30

PARAMETER PASSING

Let’s try it. Reference parameters

#include <iostream>

using namespace std;

void fun (int&, int&, int&);

int main(){

int a, b, c;

a = 27; b = 10; c = 3;

fun (a, 9, b+c);

cout << a;

return 0;

}

void fun (int &x, int &y, int &z){

x = x + y + z;

}

FUNCTIONS & DATA

21

WHAT HAPPENS?

22 of 30

PARAMETER PASSING

#include <iostream>

using namespace std;

void fun (int&, int&, int&);

int main(){

int a, b, c;

a = 27; b = 10; c = 3;

fun (a, 9, b+c);

cout << a;

return 0;

}

void fun (int &x, int &y, int &z){

x = x + y + z;

}

main.cpp:7:1: error: no matching function for call to 'fun' fun (a, 9, b+c);

^~~ main.cpp:3:6: note: candidate function not viable: expects an lvalue for 2nd argument

void fun (int&, int&, int&); ^

1 error generated.

FUNCTIONS & DATA

22

WHAT HAPPENS?

23 of 30

PARAMETER PASSING

Overview

FUNCTIONS & DATA

23

Passing by Value

Passing by Reference

int x;

int &x;

Formal parameter is a local variable

Formal parameter is a local reference

Formal parameter is a duplicate of the actual parameter

Formal parameter is a synonym for the actual parameter

Formal parameter cannot change the actual parameter

Formal parameter can change the actual parameter

Actual parameter may be constant, variable, or expression

Actual parameter must be a variable

Actual parameter is read-only

Actual parameter is read-write

24 of 30

INPUT AND OUTPUT PARAMETERS

How would we use input parameters in the “Student Grading” program?

FUNCTIONS & DATA

24

25 of 30

INPUT AND OUTPUT PARAMETERS

How would we use input parameters in the “Student Grading” program?

Say we use a function to read data from the DAT file:

int EnterStudentData(string &ID, string&name, int&G1, int &G2, int &G3, int &G4)�{

...}

FUNCTIONS & DATA

25

26 of 30

INPUT AND OUTPUT PARAMETERS

How would we use input parameters in the “Student Grading” program?

FUNCTIONS & DATA

26

in main:

While(EnterStudentData(ID, name, G1, G2, G3, G4)){

...}

27 of 30

INPUT AND OUTPUT PARAMETERS

Input parameters send data to a function, e.g., in sqrt(x), x is an input parameter. The output from the function is the function itself which returns with the value of the square root. This is just like mathematical functions: y=f(x)

 

Some functions do not return any value and so are of type void.

Some functions must return more than one output value, and we cannot use the function itself to return more than one value. We do this using output parameters, passed by reference.

FUNCTIONS & DATA

27

28 of 30

I/O PARAMETERS - EXAMPLE

//inoutparms.cpp

//modified from Hubbard, ex. 4.17, p. 107

//PROBLEM: COMPUTE THE AREA AND CIRCUMFERENCE OF A CIRCLE

 

#include <iostream>

void ComputeCircle(double, double&, double&);

 

int main(){

double radius, area, circumference;

cout << "Enter radius: "; cin >> radius;

ComputeCircle(radius, area, circumference);

cout << "\n\nWith a radius of " << radius << endl

<< "Area= " << area << endl

<< "Circumference= " << circumference << endl;

return 0;

} //end main

 

void ComputeCircle(double r, double &a, double &c) {

const double PI = 3.141592653589793;

a = PI * r * r;

c = 2 * PI * r;

} //end ComputeCircle

FUNCTIONS & DATA

28

29 of 30

SUMMARY – THE WALL AND THE WINDOW

ABSTRACTION:

INFORMATION HIDING:

FUNCTIONS & DATA

29

FN prototype

I

O

Local variables

Local parameters

Value parameters

Reference parameters vs global variables

30 of 30

REVIEW

    • External variables
    • Global variable
    • Local variable
    • Automatic variable
    • Static variable
    • Parameter
    • Argument
    • Actual parameter
    • Formal parameter
    • Value parameter
    • Variable parameter
    • Reference parameter
    • Passing by value
    • Passing by variable
    • Passing by address
    • Passing by reference
    • Value-returning function
    • Non-value-returning function
    • Void function
    • Input parameter
    • Output parameter
    • I / O parameter
    • Side effect
    • Lifetime
    • Scope
    • Storage class
    • lvalue

FUNCTIONS & DATA

30

What did we learn in this lecture? Plenty. Some terms to jog your memory: