What are the issues that may arise if variables are declared
globally, rather than being declared locally? State and discuss a
C++ code example.
Are there any rules that should be followed in determining the
scope of a variable? If so, what are they?
Issues with global variables:
Issues With Global Variables:
Following is the c++ example:
#include <iostream>
// variables declared outside of a block are global variables
int x; // global variable x
const int y; //global variable y
void seeThem()
{
// global variables can be seen and used everywhere in program
x =3;
std::cout << y << endl;
}
int main()
{
seeThem();
// global variables can be seen and used everywhere in program
x = 5;
std::cout << y << endl;
return 0;
}
Rules that should be followed in determining the scope of a variable:
Rule 1:
The scope of an entity is the program or function
in which it is declared.
There is a direct consequence of Scope Rule 1. Since an entity declared in a function has a scope of that function, this entity cannot be seen from outside of the function.
Rule 2:
A global entity is visible to all contained functions,
including the function in which that entity is declared.
Rule 3:
An entity declared in the scope of another entity is always
a different entity even if their names are identical.
Get Answers For Free
Most questions answered within 1 hours.