0% found this document useful (0 votes)
103 views44 pages

TBB1073 - SPDB05

The document provides an overview of functions in C++. It discusses: 1. The objectives of learning functions which include implementing functions, parameter passing, decomposing tasks, determining variable scope, and using value and reference parameters. 2. What functions are and how they allow dividing programs into smaller, more manageable pieces. Functions are invoked through function calls where arguments provide needed information. 3. The different types of functions including predefined standard library functions and user-defined functions. Functions may return a value or be defined as void. Parameters pass information into a function.

Uploaded by

Cyrus Hong
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views44 pages

TBB1073 - SPDB05

The document provides an overview of functions in C++. It discusses: 1. The objectives of learning functions which include implementing functions, parameter passing, decomposing tasks, determining variable scope, and using value and reference parameters. 2. What functions are and how they allow dividing programs into smaller, more manageable pieces. Functions are invoked through function calls where arguments provide needed information. 3. The different types of functions including predefined standard library functions and user-defined functions. Functions may return a value or be defined as void. Parameters pass information into a function.

Uploaded by

Cyrus Hong
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

TBB1073 - SPDB

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

Divide and conquer


Construct a program from smaller pieces or components Each piece more manageable than the original program

More about Function

Programs written by

combining new functions with prepackaged functions in the C++ standard library. The standard library provides a rich collection of functions.

Functions are invoked by a function call

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

Predefined Function: The use of C++ standard library function


pow(2,3) sqrt(4.0)

User-defined Function: Programmers create function to organize/divide tasks in a program


6

Calling a Function

Execution flow during a function call

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

double cube_volume(double side_length)


9

Implementing Functions

10

User-Defined Functions
1.Value-returning functions: have a return type

Return a value of a specific data type using the return statement


2.Void functions: do not have a return type Do not use a return statement to return a value

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

Syntax: return Statement


The return statement has the following syntax:

In C++, return is a reserved word


When a return statement executes Function immediately terminates Control goes back to the caller When a return statement executes in the function main, the program terminates

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

Format for function definition:

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

int add(int b, int c){

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; }

int add(int b,int c,float d) { int m = b+c-d; return m; }

18

19

20

Function Prototype (continued)

21

Functions Without Return Values Void Functions


Consider the task of writing a string with the following format around it. Any string could be used. For example, the string "Hello" would produce:

------!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

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

Void Functions (Example)


//Function prototype

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

Void Functions (Example)


1
void add(int b, int c) { int tot = b+c; cout << tot; } int main() { int b=3, c=4; add(b, c); return 0; } void add(int,int,float); int main() { add(3, 1, 2.3); return 0; } void add(int b,int c,float d) { cout << b+c-d; }

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.

But there are other blocks.

31

Variable Scope Nested Blocks


However, you can define another variable with the same name in a nested block.
double withdraw(double balance, double amount) { if (...) { double amount = 10; ... } ... }

a variable named amount local to the ifs block and a parameter variable named amount.
32

Variable Scope Nested Blocks


The scope of the parameter variable amount is the entire function, except the nested block. Inside the nested block, amount refers to the local variable that was defined in that block.

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.

They are visible to every function defined after them.


Generally, global variables are not a good idea.

But
heres what they are and how to use them

(if you must).

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; }

functions update global variables, the result can be difficult to predict.


36

Global Variables Just Say No


You should global variables in your programs!

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; }

Program chooses function by signature


- signature determined by function name and parameter types Can have the same return types

38

1 2// Using overloaded functions 3#include <iostream> 4 5 6 7 8int 9


10

Functions have same name but different parameters

square( int x ) { return x * x; }

double square( double y ) { return y * y; }

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;

The square of integer 7 is 49 The square of double 7.5 is 56.25


39

Parameters: Reference & Values

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

void change(int &variable){ variable += 3; }

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

void getData(int &p_id, string &p_name)

{
cout << Enter id:; cin >> p_id; cout << Enter last name:;

cin >> p_name;


}

int main() { int id; string name; getData(id,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;

int main() } { int a = 10, b = 20; swap(a,b);

cout << "Value of a is " << a <<endl; cout << "Value of b is " << b << endl; return 0; }
43

Summary

Understand the philosophy of Functions Functions Constructs

Function Definitions
Function Header (Return-value-type, Function-name, Parameter-list) Function Body

Function Prototypes Function Calls

A local variable and global variable Function Overloading Pass-by-value VS. Pass-by-reference
44

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy