Вы находитесь на странице: 1из 5

Object Oriented Programming

OBJECTIVE:

Lab

2

Scope, functions

CLO 2 PLO 1

TE-53

Scope of a variable ( local vs global)

Why global variables are evil

Static variable in a function/blocks

Passing arguments by value , passing arguments by reference, passing arguments by const reference

1. Scope and Lifetime of a variable

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.

2. Why global variables are evil

Global variables should be avoided for several reasons, but the primary reason is because they increase your program’s 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, you’d 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

3. Local Variables vs Global Variables

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.

Object Oriented Programming

4. Static Local Variables

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.

5. Static Global Variables

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.

6. Arguments passed by value and by reference.

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 don’t 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!

Object Oriented Programming

Lab task 2 Functions, scope, reference

TE-53

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:

Scope of a variable ( local vs global)

Why global variables are evil

Static variable in a function/blocks

Passing arguments by value , passing arguments by reference, passing arguments by const reference

Section 1: Local vs. Global Scope

Q1) Write a void function named swap that takes two integers x and y as arguments and swap the values of both in such a way that value of y is assigned to x and value to x is assigned to y(e.g x=8, y=7 the swap function should make x=7 and y=8). The function prints the values of x and y after swapping. In main(), define two integer variable with same names x and y, get their values from the user, print their values ,now call swap function from the main and again print the values of x and y? Are x and y in swap function values are same as in main, if not mention the reason in comments.

Q2) Why are the global variables called evil?

Object Oriented Programming

Q3)

Display the output of the give code segment

TE-53

#include <iostream.h>

void myFunc();

int main()

{

int x = 5; cout << "\nIn main x is: " << x;

myFunc();

cout << "\nBack in main, x is: " << x; return 0;

}

void myFunc()

{

int x = 8; cout << "\nIn myFunc, local x: " << x << endl;

{

 

cout << "\nIn block in myFunc, x is: " << x;

int x = 9;

cout << "\nVery local x: " << x;

}

cout << "\nOut of block, in myFunc, x: " << x << endl;

}

Static variable in a function/blocks

The static keyword is probably the most confusing keyword in the C++ language. This is because it has different meanings depending on where it is used. When applied to a variable declared outside of a block, it changes the variable from a global variable to a file scoped variable (meaning that it is visible for the file you made other files can’t assess it). When applied to a variable declared inside a block, it has a different meaning entirely.

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

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 doesn’t return anything and takes no

Q5)

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(). Repeat the above question with nValue defined as a integer. Observe the difference between the two and write down the difference in comments?

Passing Arguments by Value, Reference, const Reference

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 don’t 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!

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

Q7)

otherwise return 0. (Hint: Use the division and modulus operators to separate the number into its individual digits.) 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.