Some important points about scope here. This is taken from c++ in a nutshell but I wonder if it is exactly true or properly explained as the behavior is not quite what I expected from the description.
#include <iostream> #include <ostream> using namespace std; /* This is an abuse of the scope rules. A scope is a region of code that can have associated declarations and each declaration adds a name to a scope. The compiler works out what scope its in and then checks what names exist to use it. Scopes include objects, functions, classes etc (stuff in curly {} brackets??). Some scopes are named - e.g. functions, classes - some are unnamed e.g. statement blocks such as if statements and for loops. You can use the :: qualifier in front of a name to tell which scope to look at but most names are unqualified so the computer has to work out what scope and then what name to look at. With nested scopes NAMES IN INNERSCOPES CAN HIDE NAMES IN OUTER SCOPES! The below will print out "in contrast ...10" 10 times and then print out both "x in this scope.." and "in contrast..." 20 times. For the first ten times the inner scope is not created so x is 10, then once x in the outscope is more than 10 the inner scope x is created. */ int main() { for (int i = 0; i < 30; i++){ int x = 10; if (x < i){ double x = 3.14; cout << "x in this scope is " << x << " and i is " << i << " and double x is " << x * 2 << endl; } cout << " in contrast x in this scope is " << x << " and i is " << i << endl; } return 0; }
No comments:
Post a Comment