21
CMSC 202 Lesson 5 Functions I

CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Embed Size (px)

DESCRIPTION

C++ Functions Predefined Functions  cmath library sqrt(x) – takes the sqrt of x pow(x, n) – computes x n  cstdlib library abs(x) – integer absolute value exit(x) – end program  assert library assert(z) – ends program if z is false  Tip: pay attention to the parameter types for these! The libraries are VERY particular

Citation preview

Page 1: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

CMSC 202

Lesson 5Functions I

Page 2: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Warmup

Use setw() to print the following (in tabular format)

Fred FlintstoneBarney RubbleBugs BunnyDaffy Duck

Page 3: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

C++ Functions

Predefined Functions cmath library

sqrt(x) – takes the sqrt of x pow(x, n) – computes xn

cstdlib library abs(x) – integer absolute value exit(x) – end program

assert library assert(z) – ends program if z is false

Tip: pay attention to the parameter types for these! The libraries are VERY particular

Page 4: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Functions

You are familiar with functions that… Return a value Do not return a value (void) Have parameters (primitives, structs,

arrays) Have no parameters Call other functions

Page 5: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Functions

New stuff Scope (partial review…) Parameters

Call by value Call by reference Constant Default

Function return types Function overloading

Page 6: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Functions - Design

Abstraction Hiding the details… Do not need to know how a function works to

use it Pre-conditions

Comment describing constraints on parameter values to ensure proper function execution

Post-conditions Comment describing state of the program after

function execution VERY IMPORTANT!!!

Page 7: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Pre/Post-condition Example//------------------------------------------------------ // Function: ShowInterest // PreCondition: // balance is a nonnegative savings account balance // rate is the interest rate expressed as a percent // such as 5 for 5% // PostCondition: // the amount of interest for the given balance at the // given rate is displayed to cout. // if the parameters are invalid, "No Interest" is displayed //------------------------------------------------------- void ShowInterest( double balance, double rate ) {

if (balance >= 0 && rate >=0) {

// code to calculate and display interest } else {

cout << "No Interest\n"; }

}

Page 8: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Preconditions

How to write a good precondition? Describe assumptions/limitations of each parameter

Ex: denominator cannot be equal to zero Describe assumptions/limitations of the program state

Ex: global array “students” must have at least one student in it What must the function do?

Test every precondition!!! Ex:

if (denominator == 0) cerr << “Error: Denom == 0” <<

endl; Ex:

if (NbrOfStudents < 1)cerr << “Error: NbrOfStud < 1”

<< endl;

Page 9: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Preconditions

How to deal with unmet preconditions? Handle the error by returning a “safe”

value or printing an error Prefer NOT to print errors from functions!

Return a status value Throw an exception (later…) Last resort: Abort the program (exit or

assert)

Page 10: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Postconditions

How to write a good postcondition? Describe all possible message from the function

Ex: Error message is printed if preconditions are violated

Describe all possible return values Ex: Return value is 0 if an error is encountered,

otherwise, a positive value representing the current rate calculated is returned

What must the function do? Functionality must match postcondition claims!

Page 11: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Scope Area of a program where a variable is defined

Denoted with { } Can be nested

Types of Scope Global Scope

Outside of all functions Entire file can use global variables

Local Scope Within a pair of { } Only other code within the { } can use these If name conflict, overrides the outer-scope

Getting back to global? :: scope resolution operator Accesses global variable if name conflict

Page 12: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Scope Issues

int a = 1;int doubleVal(int a){

return 2 * a;}

int main(){

a = doubleVal(a + 7);{

char a = ‘a’;a = a + 1; // ‘a’ + 1 => ‘b’::a = ::a + 1; // 16 + 1 => 17

}return 0;

}

Page 13: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Scope Rules

Variables can be declared anywhere Declare them when you need them…

Global variables should always be constant! Not all constants should be global

For loops – initializer list is scoped inside the for loop for (int i = 0; …) // i is INSIDE the loop

Try to avoid reusing variable names…

Page 14: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Function Parameters

Argument Value/variable passed IN to a function

Parameter (or Formal Parameter) Variable name INSIDE the function

Call-by-Value Changes to the parameter do not affect the

argument Syntax:

retType funcName( type varName, … ){ … }

Page 15: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Call by Value Examplevoid mystery(int b){

b++;cout << b << endl;

}

int main(){

int a = 7;mystery(a);

cout << a << endl;return 0;

}

b : 7

a : 7

Copy value

Allocate

Allocate

Page 16: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Call by Reference

Call by Reference Changes to the parameter change the

argument Function declares that it will change

argument Share memory

Essentially a pointer Syntax:

retType funcName( type &varName, … ){ … } Look familiar?

Works “backwards”

Page 17: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Call by Reference Examplevoid mystery(int &b){

b++;cout << b << endl;

}

int main(){

int a = 7;mystery(a);

cout << a << endl;return 0;

}

a : 7Allocate

Use this space

b:

Page 18: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Value versus Reference?

Why choose value or reference? Value

Data going in, nothing coming out Only one piece of data coming out (return it!)

Reference Need to modify a value Need to return more than one piece of data Passed an array (by default are by reference,

no ‘&’ needed)

Page 19: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Call-by-Reference – Issue! What happens in the following?

void mystery(int &b){

b++;cout << b << endl;

}

int main(){

mystery(6);

return 0;}

Page 20: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Practice What is printed in the following code block?

void mystery(int a, int &b){

a++;b++;cout << a << “ “ << b << endl;

}

int main(){

int a = 1;int b = 1;

mystery(a, b);mystery(b, a);mystery(a, a);

cout << a << “ “ << b << endl;return 0;

}

Page 21: CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck

Challenge

Write a function named “getInfo” Accepts 3 parameters:

First name Last name Age

Ask the user to give you these 3 pieces of information Write a main function that will use getInfo to retrieve

this information

Think about: Will you use value or reference?