Professional Documents
Culture Documents
Lab 2
Scope, functions
CLO 2 PLO 1
OBJECTIVE:
The Scope of a particular variable is the range within a program's source code in which that variable is
recognized by the compiler. When scope rules are violated, errors will be generated during the
compilation step. Technically these errors fall in the syntax category but conceptually they result from
improper awareness of how scope rules are applied.
The Lifetime of a particular variable is the range within an executing program in which that variable is
instantiated and retains its' value. When lifetime rules are violated, no compiler errors result, rather the
program will demonstrate logic errors. Logic errors are typically much more difficult to isolate than
compiler errors.
Global variables should be avoided for several reasons, but the primary reason is because they increase
your programs complexity immensely. For example, say you were examining a program and you wanted
to know what a variable named g_nValue was used for. Because g_nValue is a global, and globals can be
used anywhere in the entire program, youd have to examine every single line of every single file! In a
computer program with hundreds of files and millions of lines of code, you can imagine how long this
would take! Second, global variables are dangerous because their values can be changed by any function
that is called, and there is no easy way for the programmer to know that this will happen
Variables are categorized as either local or global solely based on there they are declared: inside a block
out outside all blocks. A block is any code fragment enclosed in an left curly brace, {, and a right curly
brace, }. Local variables are declared in a block. Global variables are declared outside of all blocks. A local
variable is limited in scope to all the code below the declaration until the end of the enclosing block. The
variable is also visible to any other blocks that are enclosed in the original block. A global variable is not
limited in scope. This type of variable is visible to every module in the project. A commonly bemoaned
shortcoming of C++ is the exposure created by using global variables. This situation is usually avoided by
prohibiting the use of global variables and instead passing information between modules in the form of
function/method parameters.
1
Object Oriented Programming TE-53
A variant of the 'normal' local variable is the static local. By prepending the keyword static to the
variable declaration, a programmer can alter the lifetime of the variable. This keyword causes the
compiler to preserve the value of the variable even when it goes out of scope; the lifetime becomes the
entire execution of the program.When program execution reenters the blockn in which the variable is
declared, the variable still has the value it had when execution last left that block.
A variant of the 'normal' global variable is the static global. Static global variables are visiible to all
methods/functions in the module where the variable is declared, but not visible to any other modules in
the project. This strategy greatly reduces the opportnities for logic errors in larger programs. Some
coding standards endorse static global variables while discouraging non-static global variables. By doing
this a mechanism for sharing information within a module is still provided. As long as modules are kept
small and manageable, this strategy may prove useful. The final decision is left to the reader.
Until now, in all the functions we have seen, the arguments passed to the functions have been passed by
value. This means that when calling a function with parameters, what we have passed to the function
were copies of their values but never the variables themselves. One of the major disadvantages of pass
by value is that all arguments passed by value are copied to the parameters. When the arguments are
large structs or classes, this can take a lot of time. References provide a way to avoid this penalty. When
an argument is passed by reference, a reference is created to the actual argument (which takes minimal
time) and no copying of values takes place. This allows us to pass large structs and classes with a
minimum performance penalty. However, this also opens us up to potential trouble. References allow
the function to change the value of the argument, which in many cases is undesirable. If we know that a
function should not change the value of an argument, but dont want to pass by value, the best solution
is to pass by const reference. You already know that a const reference is a reference that does not allow
the variable being referenced to be changed. Consequently, if we use a const reference as a parameter,
we guarantee to the caller that the function will not (and cannot) change the argument!
2
Object Oriented Programming TE-53
Lab task 2
Functions, scope, reference
Objectives:
In the previous lab, you learnt about implementing simple functions, difference between prototype,
function definition and function call, user defined functions and built-in functions. The purpose of this
lab is to gain an understanding of the following:
3
Object Oriented Programming TE-53
#include <iostream.h>
void myFunc();
int main()
{
int x = 5;
cout << "\nIn main x is: " << x;
myFunc();
void myFunc()
{
int x = 8;
cout << "\nIn myFunc, local x: " << x << endl;
{
cout << "\nIn block in myFunc, x is: " << x;
int x = 9;
By default, local variables have automatic duration, which means they are destroyed when the block they
are declared in goes out of scope. You can explicitly declare a variable as having automatic duration by
using the auto keyword, though this is practically never done because local variables are automatic by
default, and it would be redundant.
Using the static keyword on local variables changes them from automatic duration to fixed duration
(also called static duration). A fixed duration variable is one that retains its value even after the scope in
4
Object Oriented Programming TE-53
which it has been created has been exited! Fixed duration variables are only created (and initialized)
once, and then they are persisted throughout the life of the program.
Q4) Write a function named IncrementAndPrint() that doesnt return anything and takes no
arguments. Define a variable named nValue of integer type within that function and initialize it by
one within the function, post increment the value of nValue with in the function and printt the
value of nValue. Call the function 3 times from the main().
Q5) Repeat the above question with nValue defined as a integer. Observe the difference between the
two and write down the difference in comments?
Q6) A palindrome is a number or a text phrase that reads the same backwards as forwards. For example,
each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a
function that take in a five-digit integer as input and return 1 if the number is a palindrome
otherwise return 0. (Hint: Use the division and modulus operators to separate the number into its
individual digits.)
Q7) Repeat the above but this time the function takes in a five-digit integer and variable result of integer
type passed by reference and returns nothing, In main program print the result obtained.
Q8) Re-implement the swap function with both integers passed by reference this time.
Q9) Write a function called computeCircle() that is passed three float argument (two by reference and
one by value).
void computeCircle(float& a, float& c, float r)
This function calculate the area and circumference c of the circle with given radius r and assign it to
a and c respectively. Write a main() program to exercise this function.
Re-write the above program/function that is passed three float arguments (two by reference and one
by const reference ) void computeCircle(float& a, float &c, const float&r). Try to change the value of r ,
and display the errors thrown by compiler.