Monday, May 21, 2007

Variable Scope

A given variable is said to have a scope from where it is accessible.
· Local Variables
· Global Variables
Variables whose scope covers a single function are known as local variables.
Global Variables covers multiple functions. The variable is defined as follows:
Static string myString();
Note: For Global Variables, you must either use static or const keyword.

How do you refer to the global variable when you have the local and global variables with the same name in the program?
If you have both the local and global variables with the same name “myString”, you access the global variable in the program with the à Program.myString.

Note that the scope of variables also applies to those in branching and looping structures.
Note: The variable must be declared and initialized before use. Simply declaring a variable doesn’t do much. It is only when values are assigned to the variable then that values are allocated a place in memory to be stored. When the allocation takes place inside a loop, the value is defined as a local values and goes out of scope outside of the loop. Assigning a value outside of the loop ensures that the value is local to the main code, and it is still in scope inside the loop.

No comments: