The Life of Variables.

These entities can be found everywhere in programs, from those who live a more global existence, to others found in more secluded,  localized environs. All lead a busy yet tumultuous life, coming to life when a function is put into memory, and vanishing when that function ends.

Life for variables it seems, is precarious.

Variables, or rather the entities that store data in a program usually have some form of lifespan, i.e. they are created, and ultimately destroyed. If they persisted forever then when a program ends, the memory would be “lost”, until such time as the physical memory fills up and the system crashes – not an ideal scenario! So what does scope mean?

The scope of a variable is the region of the program in which statements may refer to that variable, or change its contents. Consider the example program below:

1   #include <stdio.h>
2
3   int x=7;
4   int main(void)
5   {
6       double y;
7       y = 1.2;
8       int z;
9       z = x; 
10      return 0;
11  }

The variable x is considered a global variable. Global variables are declared in the region following the pre-processor statements, but before the main function is declared. The whole program has access to these variable. Both variables y and z are considered local variables. They can only be used within main, and only in the order in which they are declared. So the variable y is declared, and is assigned the value 1.2 (on line 7). It would not be possible to assign y the value of z on line 7, because z has not yet been declared. However assigning z the value of x on line 9 is possible, because x is a global variable.

NOTE: In general you should avoid using global variables due to the fact that they can potentially be modified from anywhere in the program. There is the possibility of the value if a global variable changing unexpectedly, resulting in a subtle error which can be extremely difficult to locate, since the offending line could be anywhere in the program.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s