0% found this document useful (0 votes)
37 views52 pages

Chapter 4

The document discusses functions in C++. It explains that functions allow programmers to break programs into segments that perform well-defined tasks. Functions can call other functions, and any function can call any other. Functions are declared with a name and parameters, and defined with a body. Parameters can be passed by value, address, or reference. Functions can return values or not. Variables have scope within blocks, functions, files, or entire programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views52 pages

Chapter 4

The document discusses functions in C++. It explains that functions allow programmers to break programs into segments that perform well-defined tasks. Functions can call other functions, and any function can call any other. Functions are declared with a name and parameters, and defined with a body. Parameters can be passed by value, address, or reference. Functions can return values or not. Variables have scope within blocks, functions, files, or entire programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Object Oriented

Programming
with C++

Reema Thareja

© Oxford University Press 2015. All rights reserved.


Chapter Four
Functions

© Oxford University Press 2015. All rights reserved.


INTRODUCTION
• C++ enables programmers to break up a program into
segments commonly known as functions.
• Each function can be written more or less independently of the
others. Every function in the program is supposed to perform a
well-defined task.
• It is not necessary that the main() can call only one function. It
can call as many functions as it wants and as many times as it
wants.
• Any function can call any other function

© Oxford University Press 2015. All rights reserved.


NEED FOR FUNCTIONS
• Dividing the program into separate well-defined functions facilitates each
function to be written and tested separately.
• Understanding, coding, and testing multiple separate functions are far
easier than doing the same for one huge function.
• All libraries in C++ contain a set of functions that programmers are free to
use in their programs.These functions have been prewritten and pretested.
• When a big program is broken into comparatively smaller functions,
different programmers working on that project can divide the workload by
writing different functions.
• Like C++ libraries, programmers can also make their functions and use
them from different points in the main program or any other program that
needs its functionalities.

© Oxford University Press 2015. All rights reserved.


USING FUNCTIONS
• A function, f , that uses another function g, is known as the
calling function and g is known as the called function.
• The inputs that the function takes are known as arguments or
parameters.
• When a called function returns some result back to the calling
function, it is said to return that result.
• The calling function may or may not pass parameters to the
called function.
• If the called function accepts the arguments, the calling
function will pass parameters, otherwise, it will not do so.
• Function declaration is a declaration statement that identifies
a function with its name, a list of arguments that it accepts,
and the type of data it returns.

© Oxford University Press 2015. All rights reserved.


USING FUNCTIONS
• Function definition consists of a function header that
identifies the function, followed by the body of the function
containing the executable code for that function.

© Oxford University Press 2015. All rights reserved.


FUNCTION DECLARATION OR FUNCTION PROTOTYPE

• function_name is a valid name for the function.


• return_data_type specifies the data type of the value that will
be returned to the calling function as a result of the processing
performed by the called function.
• data_type variable1, data_type variable2, … is a list of
variables of specified data types.
• After the declaration of every function, there is a semicolon.
• The name of the function is global.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
FUNCTION DEFINITION

© Oxford University Press 2015. All rights reserved.


FUNCTION CALL

• Function name and the number and type of arguments in the function call must
be the same as that given in the function declaration and function header of the
function definition.
• If, by mistake, the parameters passed to a function are more than specified to
accept, then the extra arguments will be discarded.
• If, by mistake, the parameters passed to a function are less than specified to
accept, then the unmatched argument will be initialized to some garbage value
(i.e. arbitrary meaningless value).
• Names, and not the types, of variables in function declaration, function call, and
header of function definition may vary.
• Arguments may be passed in the form of expressions to the called function.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
RETURN STATEMENT

• The return statement is used to terminate the execution of a


function and return control to the calling function.
• When the return statement is encountered, the program
execution resumes in the calling function at the point
immediately following the function call.
• A return statement may or may not return a value to the calling
function.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
PASSING PARAMETERS TO THE FUNCTION
• When a function is called, the calling function may have to pass
some values to the called function.
• There are two ways in which arguments or parameters can be
passed to the called function.
• They include the following:
• Call-by-value, in which values of the variables are passed by the
calling function to the called function. The programs that we have
written so far call the function using call-by-value method of
passing parameters.
• Call-by-address, in which the address of the variables is passed
by the calling function to the called function.
• Call-by-reference , in which a reference of the variable is passed
by the calling function to the called function.

© Oxford University Press 2015. All rights reserved.


Call-by-Value
• In this method, the called function creates new variables to
store the value of the arguments passed to it.
• Therefore, the called function uses a copy of the actual
arguments to perform its intended task.
• If the called function is supposed to modify the value of the
parameters passed to it, then the change will be reflected only
in the called function.
• In the calling function, no change will be made to the value of
the variables.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
Call-by-Address
• The call-by-pointer or call-by-address method of passing
arguments to a function copies the address of an argument into
the formal parameter.
• The function then uses the address to access the actual
argument. This means that any changes made to the value
stored at a particular address will be reflected in the calling
function also.
• The called function uses pointers to access the data. In other
words, the dereferencing operator is used to access the
variables in the called function.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
Call-by-Reference
• When the calling function passes arguments to the called function
using call-by-value method, the only way to return the modified
value of the argument to the caller is by using the return
statement explicitly.
• A better option when a function can modify the value of the
argument is to pass arguments using call-by-reference technique.
• In call-by-reference, we declare the function parameters as
references rather than normal variables.
• When this is done, any changes made by the function to the
arguments it received are visible by the calling program.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
DEFAULT ARGUMENTS
• When a function is specified with default arguments, the function
can be called with missing arguments.
• When a function is called with a missing argument, the function
assigns a default value to the parameter.
• This default value is specified by the programmer in the function
declaration statement.
• While specifying the default values during function declaration, the
programmer must keep the following in mind.
• Only trailing arguments can have default values; therefore, specify
them from right to left.
• No argument specified in the middle can have default values.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
RETURN BY REFERENCE
• This allows a function to be used on the left side of an
assignment statement.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
PASSING CONSTANTS AS ARGUMENTS
• When parameters are passed by reference parameter, the called
function may intentionally or inadvertently modify the actual
parameters.
• However, at times, the programmer may strictly want the actual
parameters not to be modified by the called function.
• In such cases, a constant parameter must be passed.
• Therefore, using the const keyword allows programmers to achieve
performance benefits while ensuring that the actual parameter is not
modified.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
VARIABLES SCOPE
• In C++, all constants and variables have a defined scope.
• By scope, we mean the accessibility and visibility of variables at
different points in the program.
• A variable or a constant in C++ has four types of scope—block,
function, file, and program scope.
Block Scope
 A statement block is a group of statements enclosed within an
opening and closing curly brackets ({ }).
 If a variable is declared within a statement block, as soon as the
control exits that block, the variable will cease to exist.
 Such a variable also known as a local variable is said to have a
block scope.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
VARIABLES SCOPE
Function Scope
• Function scope indicates that a variable is active and visible
from the beginning to the end of a function.
• In C++, only the goto label has function scope.
Scope of the Program
• If you want the functions to be able to access some variables
which are not passed to them as arguments, declare those
variables outside any function blocks. Such variables are
commonly known as global variables.
• Global variables are those variables that can be accessed from
any point in the program.

© Oxford University Press 2015. All rights reserved.


VARIABLES SCOPE

File Scope
• When a global variable is accessible until the end of the file,
the variable is said to have file scope.
• To allow a variable to have file scope, declare that variable
with the static keyword before specifying its data type as
follows:

• A global static variable can be used anywhere from the file in


which it is declared but it is not accessible by any other files.
Such variables are useful when the programmer writes his own
header files.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
STORAGE CLASSES
• The storage class of a variable defines the scope or visibility and life time
of variables and/or functions declared within a C++ program.

© Oxford University Press 2015. All rights reserved.


INLINE FUNCTIONS
• The major difference between an ordinary function and an inline
function is that when an inline function is called, the compiler places
a copy of its code at each point of call.
• As in case of an ordinary function, the compiler does not have to
jump to the called function.
• This saves the function call overhead and results in faster execution
of the code.
• We can make a function inline by taking caring of two aspects as
follows:
• First, write the keyword inline before the function name.
• Second, define that function before any calls are made to it.

© Oxford University Press 2015. All rights reserved.


INLINE FUNCTIONS
• However, the programmer must not forget that keyword inline
just makes a request to the compiler to make the function
inline (and place its code at each point of call).
• The compiler may ignore the request if the function has too
many lines.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
ADVANTAGES
• An inline function generates faster code as it saves the time
required to execute function calls.
• Small inline functions (three lines or less) create less code
than the equivalent function call as the compiler does not have
to generate code to handle function arguments and a return
value.
• Inline functions are subject to code optimizations that are
usually not available to normal functions as the compiler does
not perform inter-procedural optimizations.
• Inline function avoids function call overhead. As a result, we
need to save variables and other program parameters on the
system stack.

© Oxford University Press 2015. All rights reserved.


ADVANTAGES
• Since there are no function calls, the overhead of returning
from a function is also avoided.
• It allows the compiler to apply intra-procedural optimization

© Oxford University Press 2015. All rights reserved.


DISADVANTAGES
• Size of the program increases.
• Large programs may take longer time to be executed.
• At times, the program may not fit in the cache memory.
• There may be a problem in making efficient use of CPU
registers if the inline function has many register variables.
• If the code of the inline function is modified, the entire
program needs to be re-compiled.
• Inline functions should not be used for designing embedded
systems due to memory size constraints.

© Oxford University Press 2015. All rights reserved.


COMPARISON OF INLINE FUNCTIONS WITH
MACROS
• Macro invocations skip the job of type checking; this is a must-to-
do work in function calls.
• Macros cannot return a value while a function can return a value.
• Macros use mere textual substitution which can give unintended
results due to inaccurate reevaluation of arguments and order of
operations.
• Debugging of compiler errors in case of macros is more difficult
than debugging functions.
• All constructs cannot be expressed using macros; however, with
functions, they can be expressed with ease.
• Macros have a slightly difficult syntax while the syntax of writing
function is similar to that of a normal function.

© Oxford University Press 2015. All rights reserved.


FUNCTION OVERLOADING
• Function overloading, also known as method overloading, is a
feature in C++ that allows creation of several methods with the
same name but with different parameters.
• For example, print(), print(int), and print("Hello") are overloaded
methods.
• While calling print() , no arguments are passed to the function;
however, when calling print(int) and print("Hello") , an integer and
a string arguments are passed to the called function.
• Function overloading is a type of polymorphism.

© Oxford University Press 2015. All rights reserved.


FUNCTION OVERLOADING
• Basically, there are two types of polymorphism:
• Compile time (or static) polymorphism and run-time (or
dynamic) polymorphism.
• Function overloading falls in the category of static polymorphism
which calls a function using the best match technique or overload
resolution.

© Oxford University Press 2015. All rights reserved.


MATCHING FUNCTION CALLS WITH
OVERLOADED FUNCTIONS
When an overloaded function is called, one of the following cases
occurs:
• Case 1: A direct match is found, and there is no confusion in calling
the appropriate overloaded function.
• Case 2: If a match is not found, a linker error will be generated.
However, if a direct match is not found, then, at first, the compiler
will try to find a match through the type conversion or type casting.
• Case 3: If an ambiguous match is found, that is, when the arguments
match more than one overloaded function, a compiler error will be
generated. This usually happens because all standard conversions
are treated equal.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.
Functions that Cannot be Overloaded

© Oxford University Press 2015. All rights reserved.


RECURSIVE FUNCTIONS
• A recursive function is defined as a function that calls itself to
solve a smaller version of its task until a final call is made which
does not require a call to itself.
• Every recursive solution has two major cases which are given as
follows:
• Base case, in which the problem is simple enough to be solved
directly without making any further calls to the same function.
• Recursive case, in which first the problem at hand is divided into
simpler sub parts.
• Second, the function calls itself but with sub parts of the problem
obtained in the first step.
• Third, the result is obtained by combining the solutions of simpler
sub-parts.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
ADVANTAGES
• Recursive solutions often tend to be shorter and simpler than
non-recursive ones.
• Code is clearer and easier to use.
• Recursion represents like the original formula to solve a
problem.
• Follows a divide and conquer technique to solve problems.
• In some (limited) instances, recursion may be more efficient.

© Oxford University Press 2015. All rights reserved.


DISADVANTAGES

• For some programmers and readers, recursion is a difficult


concept.
• Recursion is implemented using system stack.
• If the stack space on the system is limited, recursion to a
deeper level will be difficult to implement.
• Aborting a recursive process in midstream is slow and
sometimes nasty.
• Using a recursive function takes more memory and time to
execute as compared to its non-recursive counter part.
• It is difficult to find bugs, particularly, when using global
variables

© Oxford University Press 2015. All rights reserved.


FUNCTIONS WITH VARIABLE NUMBER OF
ARGUMENTS
• In case we need a function that should accept a variable number of
arguments, we have to design a function that accepts the data-type
and/or number of arguments at the run-time while execution and not
during compilation.
• Let us take a sample program that accepts any number of values and
then return the average.
• To write such a program, we must include the cstdarg header file to
use the following macros:
• va_list that stores the list of arguments.
• va_start to initialize the list.
• It is a macro from which we can begin reading arguments from it. It
accepts two arguments— va_list and a last named

© Oxford University Press 2015. All rights reserved.


FUNCTIONS WITH VARIABLE NUMBER OF
ARGUMENTS
argument. After the last named argument, the number of
arguments read is stored.
• va_arg returns the next argument in the list. It helps in accessing
the individual arguments
• in the list. For this, you must just need to specify the type of
argument to retrieve.
• va_end is used to clean up the variable argument list once we are
done with it.
• A function that is supposed to accept variable number of
arguments must be declared in a special way.
• Instead of writing the last argument, you must put an ellipsis (like
‘…’). Therefore, int my_func( int x, … ); means that my_func
accepts any number of arguments.
© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights reserved.

You might also like