Is this code valid C++?
Is the followi开发者_如何学Gong code valid C++?
const int var = 10;
{
int var[var]; // why doesn't this give any error ?
}
Note : The code compiles on my g++ compiler.
As-is? No. If it were in the body of a function? Yes.
The first line declares an integer constant named var
with a value of 10
.
The braces begins a new block. Within that block, a new variable is declared, named var
, which is an array of int
with a size equal to the value of the integer constant previously declared as var
(10
).
The key is that var
refers to the first variable until after the second variable named var
is fully declared. Between the semicolon following the second declaration and the closing brace, var
refers to the second variable. (If there was an initializer for the second variable, var
would begin to refer to the second variable immediately before the initializer.)
Yes the code is valid C++. Non-local var
is visible up to the point of declaration of local var
.
So int var[var]
defines a local array of 10 integers.
Yes the code is valid C++ It is a concept of SCOPE : Hiding Names
const int var = 10;
{
int var[var]; // why doesn't this give any error ?
}
I think this link clears your doubt
IN C++:
http://msdn.microsoft.com/en-US/library/9a9h7328%28v=VS.80%29.aspx
In C :
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fzexscope_c.htm
If u want deep knowledge On this : Go for this link,here the information is about Lexical versus dynamic scoping
http://en.wikipedia.org/wiki/Scope_%28programming%29
but in your code : "Scope ::" of visibility of var .Here It differs like local and non-local variable. Inside braces { x=1; } local variable . where as here {y=1;{x=1;}} ,here it differs.
helpful links
http://msdn.microsoft.com/en-us/library/b7kfh662%28VS.80%29.aspx
http://www.awitness.org/delphi_pascal_tutorial/c++_delphi/c++_scope_variables.html
精彩评论