Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code valid C++?

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.

like image 952
CuriousGuy Avatar asked Oct 13 '10 05:10

CuriousGuy


People also ask

Is C valid C++ code?

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.

Are all C programs C++ programs?

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.

Is C++ a strict superset of C?

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.

Is C++ translated to C?

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.


1 Answers

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.)

like image 71
James McNellis Avatar answered Nov 15 '22 13:11

James McNellis