Activity 7-4 -  Blocks and The Scope of a Variable in a Block



Each branch of a switch statement or of an if statement does a separate task and is considered a block.  Sometimes in a program you have a compound statement with multiple declarations of variables throughout the program.  All variables declared inside a block are local to that block.  Here is an example:

// P74.cpp - This program illustrates the scope of variables in a block

#include<iostream>
using namespace std;

int main( )
{
     int x = 10;

     for(int i = 0; i < x; i++)
     {
             int x = 5;
             cout << "i = " << i << endl;
      }
      cout << "x = " << x << endl;

      return 0;
}

Exercise 7.5
Without compiling the above program, determine its output.

Copy and paste or carefully copy the program in a file called P74.cpp.  Compile and run the program and see if you have gotten the correct answer.

Now, suppose in the program we replace the for loop with the following segment:

     for(int i = 0; i < x; i++)
     {
             x = 5;
             cout << "i = " << i << endl;
      }

What is the output of the program with this segment?  Modify the program and see if you have gotten the correct answer.