O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Scoping Revisited

Think back to the sections on variable scoping, where you learned that a variable initialized within a code block is local to that code block. Within loops and nested loops, the scoping rules still apply. Consider, for example, the following code:

int x, y;

for (x = 0; x < 10; x++)
{
       for (y = 0; y < 10; y++)
       {
              int z = nArray[x][y];
       }
       if (z == 3) // Error, z out of scope
       {
             // .. do something
       }
}

Although in this snippet z has been declared within a nested loop, its scope is restricted to the nested loop, and so will not be accessible outside it. It is important to remember this when using nested loops, especially for programmers who insist on declaring variables upon use, rather than at the head of a code block.

Declaration on ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required