Chapter 1
Chapter 1
Functions
1.1. Introduction to Modular Programming
(Functions)
• Modular programming is breaking down the design of a program into
individual components (modules) that can be programmed and tested
independently.
• It is a requirement for effective development and maintenance of
large programs and projects.
• With modular programming, procedures of a common functionality
are grouped together into separate modules.
• A program therefore no longer consists of only one single part.
• It is now divided into several smaller parts which interact and which form the
whole program.
• Modules in C++ are called functions.
• A function is a subprogram that can act on data and return a value.
Every C++ program has at least one function, main().
• When your program starts, main() is called automatically. main()
might call other functions, some of which might call still others.
• Each function has its own name, and when that name is encountered,
the execution of the program branches to the body of that function.
• When the function returns, execution resumes on the next line of the
calling function.
• Functions come in two varieties: user-defined and built-in.
• Built-in (Predefined ) functions are part of your compiler package--
they are supplied by the manufacturer for your use.
• A user-defined function are custom made functions that groups code
to perform a specific task and that group of code is given a name
(identifier).
• In this chapter we will discuss about user-defined functions.
Declaring and Defining Functions
• Using functions in your program requires that you first declare the
function and then define the function.
• The declaration tells the compiler the name, return type, and
parameters of the function.
• The definition tells the compiler how the function works.
• No function can be called from any other function that hasn't first
been declared.
• The declaration of a function is called its prototype.
Declaring the Function
• There are three ways to declare a function:
• Write your prototype into a file, and then use the #include directive to include
it in your program.
• Write the prototype into the file in which your function is used.
• Define the function before it is called by any other function. When you do
this, the definition acts as its own declaration.
Using separate prototype file
Myhe.h Hellowrold.cpp
• Although you can define the function before using it, and thus avoid
the necessity of creating a function prototype, this is not good
programming practice for three reasons.
• First, it is a bad idea to require that functions appear in a file in a particular
order. Doing so makes it hard to maintain the program as requirements
change.
• Second, it is possible that function A() needs to be able to call function B(),
but function B() also needs to be able to call function A() under some
circumstances. It is not possible to define function A() before you define
function B() and also to define function B() before you define function A(), so
at least one of them must be declared in any case.
• Third, function prototypes are a good and powerful debugging technique. If
your prototype declares that your function takes a particular set of
parameters, or that it returns a particular type of value, and then your
function does not match the prototype, the compiler can flag your error
instead of waiting for it to show itself when you run the program.
Function Prototypes
• Many of the built-in functions you use have their function prototypes
already written in the files you include in your program by using #include.
• For functions you write yourself, you must include the prototype.
• The function prototype is a statement, which means it ends with a
semicolon.
• It consists of the function's return type, name, and parameter list. The
parameter list is a list of all the parameters and their types, separated by
commas.
• Function Prototype Syntax:
return_type function_name ( [type [parameterName1] type
[parameterName2]]...);
• The function prototype and the function definition must agree exactly
about the return type, the name, and the parameter list.
• If they do not agree, you will get a compile-time error.
• Note, however, that the function prototype does not need to contain
the names of the parameters, just their types.
• A prototype that looks like this is perfectly legal:
long Area(int, int);
• The same function with named parameters might be
long Area(int length, int width);
• Note that all functions have a return type.
• If none is explicitly stated, the return type defaults to int.
• Your programs will be easier to understand, however, if you explicitly
declare the return type of every function, including main().
Defining the Function
• The definition of a function consists of the function header and its body.
• The header is exactly like the function prototype, except that the
parameters must be named, and there is no terminating semicolon.
• The body of the function is a set of statements enclosed in braces. Function
Definition Syntax
return_type function_name ( [type parameterName1], [type
parameterName2]...)
{
statements;
}
• A function prototype tells the compiler the return type, name, and
parameter list.
• Functions are not required to have parameters, and if they do, the
prototype is not required to list their names, only their types.
• A prototype always ends with a semicolon (;).
• A function definition must agree in return type and parameter list
with its prototype.
• It must provide names for all the parameters, and the body of the
function definition must be surrounded by braces.
• All statements within the body of the function must be terminated
with semicolons, but the function itself is not ended with a
semicolon; it ends with a closing brace.
• If the function returns a value, it should end with a return statement,
although return statements can legally appear anywhere in the body
of the function.
• Every function has a return type. If one is not explicitly designated,
the return type will be int.
• There is virtually no limit to the number or types of statements that
can be in a function body.
• Although you can't define another function from within a function,
you can call a function, and of course main() does just that in nearly
every C++ program.
Scope of variables
• A variable has scope, which determines how long it is available to
your program and where it can be accessed.
• There are two scopes Local and Global.
Local Variables
• Not only can you pass in variables to the function, but you also can
declare variables within the body of the function.
• This is done using local variables, so named because they exist only
locally within the function itself.
• When the function returns, the local variables are no longer available.
Local variables are defined like any other variables.
• The parameters passed in to the function are also considered local
variables and can be used exactly as if they had been defined within
the body of the function.
• Variables declared within the function are said to have "local scope."
• That means that they are visible and usable only within the function
in which they are defined.
• In fact, in C++ you can define variables anywhere within the function,
not just at its top.
• The scope of the variable is the block in which it is defined.
• Thus, if you define a variable inside a set of braces within the
function, that variable is available only within that block.
The use of local variables and parameters
Global Variables
• Global variables have global scope and are available anywhere within your
program.
• Variables defined outside of any function have global scope and thus are
available from any function in the program, including main().
• Local variables with the same name as global variables do not change the
global variables.
• A local variable with the same name as a global variable hides the global
variable, however.
• If a function has a variable with the same name as a global variable, the
name refers to the local variable--not the global--when used within the
function.
`
Variables scoped within a block
Scope resolution operator
• When a local variable has the same name as a global variable, all
references indicate to the variable name made within the scope of
the local variable.
• As shown by the above output, the local variable name takes
precedence over the global variable.
• In such cases, we can still access the global variable by using C++’s
scope resolution operator (::).
• This operator must be placed immediately before the variable name,
as in ::num. When used in this manner, the :: tells the compiler to use
global variable.
Function Arguments
• Function arguments do not have to all be of the same type.
• It is perfectly reasonable to write a function that takes an integer, two
longs, and a character as its arguments.
• Any valid C++ expression can be a function argument, including
constants, mathematical and logical expressions, and other functions
that return a value.
Using Functions as Parameters to Functions
• Although it is legal for one function to take as a parameter a second
function that returns a value, it can make for code that is hard to read
and hard to debug.
• As an example, say you have the functions double(), triple(), square(),
and cube(), each of which returns a value. You could write
• Answer = (double(triple(square(cube(myValue)))));
• An alternative is to assign each step to its own intermediate variable:
• unsigned long myValue = 2;
• unsigned long cubed = cube(myValue); // cubed = 8
• unsigned long squared = square(cubed); // squared = 64
• unsigned long tripled = triple(squared); // tripled = 196
• unsigned long Answer = double(tripled); // Answer = 392
Passing arguments
Pass by Value
• The arguments passed in to the function are local to the function.
• Changes made to the arguments do not affect the values in the calling
function.
• This is known as passing by value, which means a local copy of each
argument is made in the function.
• These local copies are treated just like any other local variables.
d
Pass by reference