%\marginsize{2cm}{2cm}{0.25cm}{2cm}  % left right top bttom?
%\pagestyle{empty}
\def\semester{Fall~2005}
\def\course{CS~101}
\def\prof{Sharat}
\newcommand{\titleline}[1]{

%  \includegraphics[scale=0.5]{e1.png}\\
% to replaced by a pattern here. - appu
% {\Huge \textbf{\textsf{B1}} \\}

  {\sc #1}\hfill{\sc \prof} \vspace{0.1cm} \hrule }

\newcommand{\exhead}[1]{
  \begin{center} {\bf \course: #1} \\ \end{center} }
  
\documentclass[10pt]{article}
\usepackage{anysize,color,graphicx}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{longtable}
% \usepackage{HW}


\begin{document}
\titleline{\semester}
\exhead{Lab Handout No: 12}

\vspace{0.25in}
\begin{itemize}
\item This assignment carries marks.
\item {\textbf{Do not look for a problem description in PEACH. Do the lab based on the handout.}}
\end{itemize}

\section{Objectives}
%% This week in the lab we will be examining parameter
%% passing. Understanding parameterized functions will enable you to
%% design functions that correctly compute and return values to your
%% program. Misuse of parameters is a common problem among programmers a
%% problem that often results in unexpected errors.
This week in lab we will be examining three concepts:
\begin{itemize}
\item Scope of variables
\item Argument Passing
\item Function Overloading
\end{itemize}

\section{Scope}
Every variable has a \emph{scope} -- a section of code within which it can be accessed. To access a variable, the variable must be \emph{in scope} -- visible -- at the point of use. For instance, a variable defined within the initializer of a for loop can't be used outside the loop, because its scope is limited to the loop:
\begin{verbatim}
for(int i = 0; i< 10; ++i)
    cout << i;
cout << "The final value of i is " << i;	//error
\end{verbatim}

i is accessible only within the loop, so the second cout is not allowed. We say that the scope of i is the loop or, in other words, i is not in scope in the second cout. So the compiler, when it sees the second cout, says, in effect, ``i? what's that?"

Not only does scoping prevent access to variables but it also allows you to have two different variables in different scopes. For instance:

\begin{verbatim}
void foo() {
    int i = 7;
    ...
    }

void bar() {
    string i = "No problem";
    ...
    }
\end{verbatim}

Here we have two variables named i, but there's no problem since they are in different scopes. If a statement within foo() accesses i, it will get foo()'s copy of i, and similarly for a statement within bar(). Changing one will not affect the other (after all, they are different variables). The two variables can be of different types and have no connection at all.

Scopes can also be nested -- you can have one scope defined within another. Here's an example:
\begin{verbatim}
void foo(int something) {
    int i = 4;
    if(something > 8) {
        string i = "what happens";
        cout << i;	//what does this print?
        }
    cout << i;	//prints 4
    }
\end{verbatim}
Here we have two variables in two different scopes -- one within the scope of the function foo(), and the other restricted to the body of the \emph{if}. What makes this example different (and interesting) from the previous one is that one scope is nested -- contained -- within the other. It should be clear that the second cout prints 4 -- that's the only i which is in scope at that point. But both i's are in scope for the first cout. So what happens? C++ resolves this by using the variable defined in the \emph{innermost} scope. If the compiler ever has to choose between two variables of the same name, it prefers the one defined in the inner scope. We say that the inner i (the string) \emph{hides} the outer one.

Scope applies to all identifiers -- names (of variables, functions, classes, etc), not just local variables.

There is also a \emph{global scope} -- it contains everything that's not defined in any other scope, including global variables and the functions themselves defined above.

\section{Argument Passing}
When a function is called, arguments are passed \emph{by value}, meaning that a copy is made and given to the called function. That's why this doesn't do what is intended:
\begin{verbatim}
void doubleThis(int i) {
    i *= 2;
    cout << i;
    }

int main() {
    int i = 7;
    doubleThis(i);
    cout << i;	//prints 7
    }
\end{verbatim}
When doubleThis() is called, a copy of its argument -- the variable i in main() -- is made and passed. The copy is doubled and printed, giving the expected result (14). But once it exits, its copy is destroyed (that's why it's called a local variable -- it's local to the function and don't persist once the function returns). Then main() prints its variable i and 7 is printed, because nobody changed its value. If you xerox something and give the copy to a friend, who then scribbles something on it, would you expect the original to change?

If you indeed want the variable in the calling function to change, pass it \emph{by reference}:
\begin{verbatim}
void doubleThis(int &i) {
    i *= 2;
    }
\end{verbatim}
Note the ampersand before the definition of i. This says that you want a reference to the original variable rather than a copy of it. Now doubleThis() works as expected.

\section{Function Overloading}
Here's a function that returns the absolute value of its argument:
\begin{verbatim}
int abs(int i) {
    if(i >= 0)
        return i;
    return -i;
    }
\end{verbatim}

But is it only integers that have absolute values? Certainly not. We'd like to have a function that gives the absolute value of a double, too. So we define it. But do we have to give this new function a different name so as not to clash with the version that operates on an int? As it turns out, no -- you can give the second funtion the same name:
\begin{verbatim}
double abs(double i) {
    if(i >= 0)
        return i;
    return -i;
    }
\end{verbatim}
When you call abs(), the compiler looks at the argument type to determine which variant of abs() to call:
\begin{verbatim}
int i = 2;
double j =4;
cout << abs(i);	//calls the int version, since the argument i is an int.
cout << abs(j);	//calls the double version, since the argument j is a double.
\end{verbatim}

To make this clear, you can add statements in the two versions of abs() that print "int version called" and "double version called".

Note that the two functions are defined within the same scope (the global scope) and are distinguished based on argument types (the return type is not taken into consideration). This is different from the previous examples where variables were in different scopes and the one defined in the innermost scope is chosen.

Function overloading is useful when we need to write
functions that perform similar tasks but need to operate on different
data type.

Here's another example:
\begin{verbatim}
void swap(int &x, int &y) {
    int tmp = x;
    x = y;
    y = tmp;
    return;
    }

void swap(double &x, double &y){
    double tmp = x;
    x = y;
    y = tmp;
    return;
    }
\end{verbatim}
If there was no function overloading, we would have been forced to
choose a different name for this function.


\section{Problems}
For each of the problems in this laboratory, perform the following
activities with your group.

\begin {itemize}
\item Read the program, but do not run it!
\item  Trace through it by hand and determine what the results of the program will be.
\item  Discuss your results with your group partner and come to a consensus on
the answer. When you have reached a consensus, then open your editor
and type in the program.
\item If your answer disagrees with the results produced when you ran
the program, go back and see why your answer was incorrect. If you
cannot figure out a problem, ask your TA for help.
\item After you get the desired output, submit the program to peach
\end {itemize}

\emph{Helpful Hint:} When you try to trace parameters by hand, it
is useful to draw boxes for each object and then write the current
value in the box. This method enables you to see what is going on with
each parameter. It also enables you to cross out an old value and
replace it with a new one every time an object is updated.

\section{Problem 1}
\begin{verbatim}
#include <iostream>
#include <string>
using namespace std;

int i = 0;
int I = 1;

void f() {

   cout << "i: " << i << endl;
   cout << "I: " << I << endl;

   i = 10;
   I = 20;
}

int main() {

   int i = 2;
   int I = 3;

   cout << "i: " << i << endl;
   cout << "I: " << I << endl;

   f();

   cout << "i: " << i << endl;
   cout << "I: " << I << endl;

   return 0;
}
\end{verbatim}
What output is produced?

\section{Problem 2}
\begin{verbatim}
#include <iostream>
#include <string>
using namespace std;


int counter = 0;

void f() {
   ++counter;
}

void g() {
   f();
   f();
}

void h() {
   f();
   g();
   f();
}

int main() {
   f();

   cout << counter << endl;
   counter = 0;

   g();

   cout << counter << endl;
   counter = 0;

   h();

   cout << counter << endl;
   return 0;
}
\end{verbatim}
What output is produced?


\section{Problem 3}
\begin{verbatim}
#include <iostream>
#include <string>
using namespace std;

int i = 0;

int main() {
   int i = 1;
   cout << "i: " << i << endl;
   
   {
      cout << "i: " << i << endl;
      int i = 2;
      cout << "i: " << i << endl;
    
      {
         cout << "i: " << i << endl;
	 int i = 3;
	 cout << "i: " << i << endl;	
      }

      cout << "i: " << i << endl;
   }

   cout << "i: " << i << endl;
   cout << "i: " <<::i << endl;

   return 0;
}
\end{verbatim}
What output is produced?


\section{Problem 4}
\begin{verbatim}
#include <iostream>
#include <string>
using namespace std;

void f(int a) {
   cout << "int a: " << a << endl;
   return;
}

void f(char a) {
   cout << "char a: " << a << endl;
   return;
}
int main() {
   int i = 1;
   char c = 'c';

   f(i);
   f(c);

   return 0;
}
\end{verbatim}
What output is produced?

\end{document}
