TBB1073 - SPDB05
TBB1073 - SPDB05
Functions
Objectives
To be able to implement functions To become familiar with the concept of parameter passing To develop strategies for decomposing complex tasks into simpler ones To be able to determine the scope of a variable To recognize when to use value and reference parameters
2
Introduction to Function
Programs written by
combining new functions with prepackaged functions in the C++ standard library. The standard library provides a rich collection of functions.
A function call specifies the function name and provides information (as arguments) that the called function needs Boss to worker analogy:
A boss (the calling function or caller) asks a worker (the called function) to perform a task and return (i.e. report back) the results when the task is done.
4
Calling a Function
A programmer calls a function to have its instructions executed.
the caller
(getting things done)
the function
(has the modify temperature instructions)
Types of Function
Calling a Function
Parameters
int main() { double z = pow(2, 3); ... }
When another function calls the pow function, it provides inputs, such as the values 2 and 3 in the call pow(2, 3). In order to avoid confusion with inputs that are provided by a human user (cin >>), these values are called parameter values. The output that the pow function computes is called the return value (not output using <<).
8
Implementing Functions
When writing this function, you need to:
Pick a good, descriptive name for the function Give a type and a name for each parameter. There will be one parameter for each piece of information the function needs to do its job. Specify the type of the return value
Implementing Functions
10
User-Defined Functions
1.Value-returning functions: have a return type
11
return Statement
Once a value-returning function computes the value, the function returns this value via the return statement It passes this value outside the function via the return statement
12
13
Value-Returning Functions
To use these functions you must: Include the appropriate header file in your program Know the following items:
1. Name of the function 2. Number of parameters, if any 3. Data type of each parameter 4. Data type of the value returned: called the type
of the function
14
Value-Returning Functions
Function header
Return-value-type Function-name ( Parameter-list ) { variable declarations Braces . Function body return expression } parameter-list for a function declaration takes the form of: Example: float square( int y, float z) type var_1, type var_2, { return y * z; }
15
Value-Returning Functions
1
int add(int b, int c); int main(){ int a = add(3,4); cout << a;
Return value
int add(int b, int c); int main() { cout << add(3,4); return 0; } int add(int b, int c) { return b+c; }
return 0; } Passing
arguments
return b+c;
}
16
Value-Returning Functions
3
int add(int b, int c); int main() { int b=3, c=4; cout << add(b,c); return 0; } int add(int b, int c) { return b+c; } int add(int b, int c); int main() { cout << add(3,4); return 0; } int add(int b, int c) { int m = b+c; return m; }
17
Value-Returning Functions
5
int add(int b, int c) { return b+c; } int main() { int b=3, c=4; cout << add(b,c); return 0; } int add(int , int, float); int main() { cout << add(3,4,1.0); return 0; }
18
19
20
21
------!Hello! -------
22
Void Functions
void box_string(string str)
Use a return type of void to indicate that a function does not return a value. void functions are used to simply do a sequence of instructions They do not return a value to the caller.
23
Void Functions
void box_string(string str) { int n = str.length(); for (int i = 0; i < n + 2; i++){ cout << "-"; } cout << endl; cout << "!" << str << "!" << endl; for (int i = 0; i < n + 2; i++) { cout << "-"; } cout << endl; }
Note that this function doesnt compute any value. It performs some actions and then returns to the caller without returning a value.
(The return occurs at the end of the block.)
24
int main ( ) { int X = 12; //Defines the integer variable prt ( X ); //Calls prt ( ) and passes it X return 0; // Returns 0 to the environment }
Passing arguments
void prt (int Y) //The prt ( ) function definition { cout << Y ; //Displays the value of Y return; //Returns no value, passes //control to main ( ) }
25
26
Variable Scope
You can only have one main function but you can have as many variables and parameters spread amongst as many functions as you need. Can you have use the same name in different functions?
27
Variable Scope
A variable or parameter that is defined within a function is visible from the point at which it is defined until the end of the block named by the function. This area is called the scope of the variable.
28
Variable Scope
The scope of a variable is the part of the program in which it is visible.
Because scopes do not overlap, a name in one scope cannot conflict with any name in another scope. A name in one scope is invisible in another scope
29
Variable Scope
double cube_volume(double side_len) { double volume = side_len * side_len * side_len; return volume; } int main() { double volume = cube_volume(2); cout << volume << endl; return 0; }
Each volume variable is defined in a separate function, so there is not a problem with this code.
30
Variable Scope
Names inside a block are called local to that block. A function names a block. Recall that variables and parameters do not exist after the function is overbecause they are local to that block.
31
a variable named amount local to the ifs block and a parameter variable named amount.
32
You should avoid this potentially confusing situation in the functions that you write, simply by renaming one of the variables. Why should there be a variable with the same name in the same function?
33
Global Variables
Global variables are defined outside any block.
But
heres what they are and how to use them
34
Global Variables
In some cases, this is a good thing: The <iostream> header defines these global variables: cin cout This is good because there should only be one of each of these and every function who needs them should have direct access to them.
35
Global Variables
int balance = 10000; // A global variable void withdraw(double amount) { if (balance >= amount) { balance = balance - amount; } } When multiple int main() { withdraw(1000); cout << balance << endl; return 0; }
avoid
37
Function Overloading
Having functions with same name and different parameters Should perform similar tasks ( i.e., a function to square ints, and function to square floats).
int square(int x) {return x * x;} float square(float x) { return x * x; }
38
11 12 int main() 13 {
14
15 16 17 18 19 }
cout << "The square of integer 7 is " << square( 7 ) << "\nThe square of double 7.5 is " << square( 7.5 )
<< endl;
return 0;
Call by value Copy of data passed to function Changes to copy do not change original Used to prevent unwanted side effects Call by reference Function can directly access data Changes affect original Reference parameter for argument & is used to signify a reference
Adds 3 to the variable inputted int y = &x. A change to y will now affect x as well
40
Passing by reference
Suppose you would like a function to get the users last name and ID number. The variables for this data are in your scope. But you want the function to change them for you. If you want to write a function that changes the value of a parameter, you must use a reference parameter. Is like passing the address of variable used as argument in function call. (Example next slide)
41
{
cout << Enter id:; cin >> p_id; cout << Enter last name:;
The function updates two values, id and name. If we use return, only one value can be returned.
cout << ID: " << id <<endl; cout << "Name: " << name << endl; return 0; }
42
void swap(int &px, int &py) { int temp; temp = px; px = py; py = temp;
cout << "Value of a is " << a <<endl; cout << "Value of b is " << b << endl; return 0; }
43
Summary
Function Definitions
Function Header (Return-value-type, Function-name, Parameter-list) Function Body
A local variable and global variable Function Overloading Pass-by-value VS. Pass-by-reference
44