Is the following 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.
If the C++ compiler provides its own versions of the C headers, the versions of those headers used by the C compiler must be compatible. Oracle Developer Studio C and C++ compilers use compatible headers, and use the same C runtime library. They are fully compatible.
C++ is a subset of C as it is developed and takes most of its procedural constructs from the C language. Thus any C program will compile and run fine with the C++ compiler. However, C language does not support object-oriented features of C++ and hence it is not compatible with C++ programs.
If you're not familiar with both languages, you might have heard people say that C++ is a superset of C. If you're experienced in both languages, you'll know that this is not true at all. Of course, C++ has many features that C does not; but there are also a few features that only C has.
Short answer: no. Modern C++ compilers generate native code directly. In neither case does the C look anything like the code you put in: it's significantly less readable than machine code would be.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With