0% found this document useful (0 votes)
13 views

05 Functions

This slide explains in detail the function of function in programming.

Uploaded by

hohuuloc40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

05 Functions

This slide explains in detail the function of function in programming.

Uploaded by

hohuuloc40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Functions

Contents
o Predefined functions
o User-defined functions
o Scope rules
o Parameters
o Function overloading
o Default arguments

fit@hcmus | Programming 1 | 2021 2


Functions
o Functions are like building blocks
o They allow complicated programs to be divided into manageable
pieces
o Some advantages of functions:
• A programmer can focus on just that part of the program and construct it,
debug it, and perfect it
• Different people can work on different functions simultaneously
• Can be re-used (even in different programs)
• Enhance program readability

fit@hcmus | Programming 1 | 2021 3


Functions
o Other names:
• Procedure
• Subprogram
• Method

o Types:
• Pre-defined functions
• User-defined (Programmer-defined) functions

fit@hcmus | Programming 1 | 2021 4


Predefined Functions
Do not reinvent the wheel.

fit@hcmus | Programming 1 | 2021 5


Predefined Functions
<data_type returned/void> Function_Name (Argument_List)
• void function: Function does not produce a value.
• Argument list: comma-separated list of arguments.

fit@hcmus | Programming 1 | 2021 6


Some Predefined Functions
o Some of the predefined mathematical functions are:
sqrt(x)
pow(x, y)
floor(x)
o Predefined functions are organized into separate libraries
o I/O functions are in iostream header
o Math functions are in cmath header
o Some functions are in cstdlib header.

fit@hcmus | Programming 1 | 2021 7


Some Predefined Functions
o pow(x,y) calculates xy
• pow(2, 3) = 8.0
• Returns a value of type double
• x and y are the parameters (or arguments). The function has two parameters.
• 8.0 is value returned.

o sqrt(x) calculates the nonnegative square root of x, for x>=0.0


• sqrt(2.25) is 1.5
• Returns the value of type double

fit@hcmus | Programming 1 | 2021 8


Some Predefined Functions
o The floor(x) function calculates largest whole number not
greater than x
• floor(48.79) is 48.0
• Type double
• Has only one parameter

o The abs(x), labs(x), fabs(x) functions calculate the absolute


value of x (x is integer, long or floating-point number).

fit@hcmus | Programming 1 | 2021 9


fit@hcmus | Programming 1 | 2021 10
Some Predefined Functions
o cos(x), cmath: return cosine of angle x.
o tolower(c), cctype: return lowercase of c.
o toupper(c), cctype: return UPPERCASE of c.

fit@hcmus | Programming 1 | 2021 11


void Predefined Functions
o exit(integer)
• Library cstdlib
• Program ends immediately.
• argument value:
• 1: caused by error
• 0: other cases.

fit@hcmus | Programming 1 | 2021 12


User-defined Functions

fit@hcmus | Programming 1 | 2021 13


Example

fit@hcmus | Programming 1 | 2021 14


Example

fit@hcmus | Programming 1 | 2021 15


Terminologies
o Function declaration/Function prototype:
• determines the kind of function
• tells the name of the functions
• tells number and types of arguments
• ends with a semicolon.
o Function definition: describes how the function works.
• Function header: same as function declaration (without semicolon at the
end).
• Function body: consists of declaration and executable statements enclosed
within a pair of braces.

fit@hcmus | Programming 1 | 2021 16


Terminologies
o Function call/Function invocation

o Formal argument (argument): variable declared in function header,


or function prototype.

o Actual argument: variable or expression listed in a function call.

fit@hcmus | Programming 1 | 2021 17


Function Declaration
o Syntax:
Type_Returned/void FunctionName(Parameter_List);

• Parameter_List can be empty (function with no arguments).

o Normally placed before the main function.

fit@hcmus | Programming 1 | 2021 18


return Statement
o 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

o Syntax:
return expression;

fit@hcmus | Programming 1 | 2021 19


return Statement
o When a return statement executes
• Function immediately terminates
• Control goes back to the caller

o A return statement in void function simply ends the function call.


• void function needs not contain

o When a return statement executes in the function main, the program


terminates.

fit@hcmus | Programming 1 | 2021 20


Examples

fit@hcmus | Programming 1 | 2021 21


Examples

fit@hcmus | Programming 1 | 2021 22


Function main
o The main part of a program is the definition of a function called main.

o When program runs, the function main is automatically called.

o Some compiler requires return 0; in the main function.

fit@hcmus | Programming 1 | 2021 23


Recursive Functions
o The function calls itself.

o Example:
int Factorial(int N)
{
if (N == 0)
return 1;
return N * Factorial(N-1);
}

fit@hcmus | Programming 1 | 2021 24


Scope Rules

fit@hcmus | Programming 1 | 2021 25


Scope of an Identifier
o The scope of an identifier refers to where in the program an
identifier is accessible.
• Local identifier: identifiers declared within a function (or block)
• Global identifier: identifiers declared outside of every function definition

o C++ does not allow nested functions


• The definition of one function cannot be included in the body of another
function

fit@hcmus | Programming 1 | 2021 26


Local Variables
o Variables are declared within the body of a function.
• Local to that function.

o Two same name (local) variables in two different functions are


different.

fit@hcmus | Programming 1 | 2021 27


Global Constants
o Use the const modifier to name constant value.
const double TAX_RATE = 0.1; //VAT tax: 10%

o If the declaration is outside of all functions, the named constant is


global named constant.

fit@hcmus | Programming 1 | 2021 28


Global Variables
o Global variable:
• same as global named constant, without using const modifier.
• accessible to all function definitions in a file.

fit@hcmus | Programming 1 | 2021 29


Global Variables
o Some compilers initialize global variables to default values
o The operator :: is called the scope resolution operator
o By using the scope resolution operator
• A global variable declared before the definition of a function (block) can be
accessed by the function (or block) even if the function (or block) has an
identifier with the same name as the variable.

fit@hcmus | Programming 1 | 2021 30


Global Variables | Example

fit@hcmus | Programming 1 | 2021 31


Side Effects
o Using global variables has side effects
• A function that uses global variables is not independent
• If more than one function uses the same global variable and something
goes wrong
• It is difficult to find what went wrong and where
• Problems caused in one area of the program may appear to be from another area

o Global named constants have no side effects.

fit@hcmus | Programming 1 | 2021 32


Blocks
o A block is some C++ code enclosed in braces.

o Variables declared in a block are local to that block.

fit@hcmus | Programming 1 | 2021 33


Blocks

fit@hcmus | Programming 1 | 2021 34


Nested Blocks
o If one identifier is declared in two blocks (nested), they are different
variables with the same name.

fit@hcmus | Programming 1 | 2021 35


Nested Blocks

fit@hcmus | Programming 1 | 2021 36


Static Local Variables
o Keyword static is used for specifying a static variable.

o Examples:
static int a;
static float b;

fit@hcmus | Programming 1 | 2021 37


Static Local Variables
o A static local variable exists only inside a function where it is
declared (like a local variable) but its lifetime starts when the
function is called and ends only when the program ends.

o The main difference between local variable and static variable is


that the value of static variable persists the end of the program.

fit@hcmus | Programming 1 | 2021 38


Static Local Variables | Example

fit@hcmus | Programming 1 | 2021 39


Example | Classifying Numbers
o We use functions to write the program that determines the number
of odds and evens from a given list of integers.
o Main algorithm remains the same:
• Initialize variables, zeros, odds, evens to 0
• Read a number.
• If number is even, increment the even count
• If number is also zero, increment the zero count; else increment the
odd count
• Repeat Steps 2-3 for each number in the list.

fit@hcmus | Programming 1 | 2021 40


Example | Classifying Numbers
o The program functions include:
• initialize: initialize the variables, such as zeros, odds, and evens
• getNumber: get the number
• classifyNumber: determine if number is odd or even (and whether it is
also zero); this function also increments the appropriate count
• printResults: print the results

fit@hcmus | Programming 1 | 2021 41


Exercises
o Assignment 12 (Page 143).

fit@hcmus | Programming 1 | 2021 42


Parameters

fit@hcmus | Programming 1 | 2021 43


Value vs Reference Parameters
o Call-by-Value parameter: a formal parameter that receives a copy
of the content of corresponding actual parameter.
• Can be variables or expressions.

o Call-by-Reference parameter: a formal parameter that receives the


location (memory address) of the corresponding actual parameter.
• Only be variables.

fit@hcmus | Programming 1 | 2021 44


Call-by-Value Parameters
o Is actually a local variable.

o The value of the corresponding actual parameter is copied into it.

o The parameter has its own copy of the data.

o During program execution


• The parameter manipulates the data stored in its own memory space.

fit@hcmus | Programming 1 | 2021 45


Call-by-Reference Parameters
o It receives the memory address of the corresponding actual
parameter.

o The parameter stores the address of the corresponding actual


parameter.

o During program execution to manipulate data


• The address stored in the parameter directs it to the memory space of the
corresponding actual parameter.

fit@hcmus | Programming 1 | 2021 46


Call-by-Reference Parameters
o Indicating the call-by-reference parameters by attaching the
ampersand sign & at the of the type name in formal parameter list.

o Example:
void getInput(double& N);
void sum(int N, int& s);

fit@hcmus | Programming 1 | 2021 47


Call-by-Reference Parameters
o Call-by-Reference parameters can:
• Pass one or more values from a function
• Change the value of the actual parameter

o Call-by-Reference parameters are useful in three situations:


• Returning more than one value
• Changing the actual parameter
• When passing the address would save memory space and time

fit@hcmus | Programming 1 | 2021 48


Example
o Write a function to swap the value of two integer variables a, b.

fit@hcmus | Programming 1 | 2021 51


Example
o Write a function to swap the value of two integer variables a, b.

o Version 01:
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}

fit@hcmus | Programming 1 | 2021 52


Example
o Write a function to swap the value of two integer variables a, b.

o Version 02:
void swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}

fit@hcmus | Programming 1 | 2021 53


Function Overloading

fit@hcmus | Programming 1 | 2021 55


Overloaded Functions
o Two or more functions having same name but different argument(s) are
known as overloaded functions.
o The signature of a function consists of the function name and its formal
parameter list.

o Examples:
int test();
void test(int);
void test(float);
int test(float);
float test();

fit@hcmus | Programming 1 | 2021 56


Overloaded Functions | Examples

fit@hcmus | Programming 1 | 2021 57


Overloaded Functions | Examples

fit@hcmus | Programming 1 | 2021 58


Default Arguments

fit@hcmus | Programming 1 | 2021 59


Default Arguments
o In a function call, the number of actual parameters and formal
parameters must be the same.
• C++ relaxes this condition for functions with default parameters

o You specify the value of a default parameter when the function


name appears for the first time (e.g., in the prototype).

o If you do not specify the value of a default parameter, the default


value is used.

fit@hcmus | Programming 1 | 2021 60


Default Arguments
o All default parameters must be the rightmost parameters of the
function.

o Default values can be constants, global variables, or function calls


• Cannot assign a constant value as a default value to a reference
parameter.
o In a function call where the function has more than one default
parameter and a value to a default parameter is not specified:
• You must omit all of the arguments to its right
fit@hcmus | Programming 1 | 2021 61
Examples

fit@hcmus | Programming 1 | 2021 62


Examples
o Illegal function prototypes:

fit@hcmus | Programming 1 | 2021 63


Examples

fit@hcmus | Programming 1 | 2021 64


Function as an Argument

fit@hcmus | Programming 1 | 2021 65


Questions and Answers

fit@hcmus | Programming 1 | 2021 66

You might also like