November 15, 2006

Loop Variable’s Scope

According to C, C++ the scope of variables in for loop is within the loop. That is, a variable inside the loop will not be accessible once the loop finishes it job! For example:

for (int i=0;i<MAX;i++) {

// do something in the loop

// variable “i” should not be accessible!

But there is another twist in this variable’s scoping. Different compilers should different behaviours in scoping of variables. I will review three compilers here: Borland CPP 3.0, Visual Studio 6.0, GCC 3 and above.

Compiler 1: (Borland C++ 3.0)

This one of the most used compiler by beginners! But I will never recommend it for starting C or C++ as its too old (released in 1989) and have troubles running with latest processors. Now, lets take an example. Consider the loop given below:

for (int i=0;i<MAX;i++) {

printf (“Value of I : %d \n”, i);

printf (“Out of loop! \n The value of i is: %d”, i);

Running this loop will give you list of “i” values and finally once the loop is complete the final value i.e., MAX will be displayed. In short we will be able to access the variable out of its scope! Is this correct? Since I found this behaviour in Borland I did a research with other compilers.

Compiler 2: (Visual Studio 6)

Visual Studio 6 from Microsoft is one of the highly professional IDE available. This IDE too shows the same behaviour. I don’t have access to the latest Microsoft IDE (.Net) so haven’t checked it out. Another important aspect of Microsoft compile is that it doesn’t follow C99 standard complete.

Compile 3: (GCC 3 and Above)

Now some the change! The same code in GCC (GNU Compiler Collection) will give you an error! You will not able to access the variable outside the loop as the scoping rule goes.

Try out the loop in GCC and see how standardized it is. If you don’t use Linux you can GCC based compiler like DEV-C++ for windows platform. For any beginners I would recommend them to study C/C++ using GCC compile and never NEVER use old Borland compilers!

No comments :