// for.cc examples of scope rules (this is one file) // SGI CC -n32 -LANG:ansi-for-init-scope=ON for.cc // an old version of C++ will give error on second for(int i=0; ... // an old version of C++ will give error on second s=7 #include // should be #include int funct(int s=7); // just a function prototype // prototype visible in this file // binary visible to everything linked int k = 1; // this is global to everything linked int main() // visible to linker, only one 'main' allowed per link { int j=0; // this is global to this file for(int i=0; i<10; i++) // 'i' declared and defined inside loop { j=j+i; // this is a local 'i' } cout << "j=" << j << " k=" << k << endl; // can not print 'i' here // int j=3; // not legal, redeclaration of 'j' int i=2; // should be OK, scope of i is just loop j = 3; k = 3; for(int i=1; i<5; i++) { j=j+k+i; // this is another 'i' local to this loop } cout << "j=" << j << " k=" << k << " i=" << i << endl; // can print 'i' before loop here j = funct(); cout << "j using default=" << j << endl; j = funct(5); cout << "j using funct(5)=" << j << endl; return 0; } // =7 should be allowed int funct(int s /* =7 */ ) // if no value for 's' then, use '7' as default { // j=5; // no. 'j' only visible inside 'main' above bool b; // check for type defined b = true; b = false; // check for enumeration literals defined k=7; // OK, global cout << "k=" << k << " b=" << b << endl; return s+k; } // Result of running this program // j=45 k=1 // j=25 k=3 i=2 // k=7 b=0 // j using default=14 // k=7 b=0 // j using funct(5)=12