next up previous
Next: Function Overloading Up: Functions Previous: Functions Returning Values

Local/Global

Functions that are declared inside a function are called local variables while global variables are variables that are known throughout the entire program and can be used by any piece of the code.

Example
#include <iostream.h>
#include <stdlib.h>
void drill();
int count; //count and num_right are global
int num_right;

main()
{
cout << "How many practice problems:";
cin >> count;
num_right=0;
do {
drill();
count-;
} while(count);
cout << "You got "<<num_right<< "right. $\backslash$n";
return 0;
}
void drill()
{
int count; /* this count is local and unrelated to the global one */
int a, b, ans; // a, b and ans are locals
// generate two numbers between 0 and 99
a=rand()%100;
b=rand()%100;

//the user gets three tries to get it right for(count=0;count<3;count++){
cout << "What is " << a << "+" <<b <<" ?";
cin >>ans;
if(ans==a+b){
cout <<"Right $\backslash$n";
num_right++ ;
return;
}
}
cout << "You have used up all your tries $\backslash$n";
cout << "The answer is "<< a+b << '$\backslash$n';
}


Yousef Haik
2/23/1998