Are arrays in C++ same as C?
Does the C++ compiler treat the arrays same way as in C?
E.g
In C,
- An array access using subscript operator is always interpre开发者_如何学Pythonted as a pointer.
- In function argument, array declarations are treated as pointer to start of element.
Yes and no. Arrays work the same in both languages for the most part (C99 supports variable-length arrays, while C++ doesn't, and there may be a few other subtle differnces as well).
However, what you're saying isn't exactly true either. The compiler doesn't treat an array access as a pointer, not even in C. An array access can be more efficient in some cases, because the compiler has better information on aliasing available in the array case. In both C and C++, a plain pointer access means that the compiler has to assume that it may alias any other compatible type. If the compiler simply treated it as a pointer dereference, then this optimization opportunity would be lost.
Edit
As pointed out in a comment, the language standard does define array subscripting in terms of pointer arithmetics/dereferencing. Of course, actual compilers make use of the additional information that a pointer is really an array, so they're not treated exactly like pointers, but that could be considered an optimization beyond what the standard mandates.
Not exactly same as in C99. C99 supports Variable Length Array (VLA), but C++ doesn't.
void f(int n)
{
int array[n]; //valid C99, but invalid C++
}
That means, C++ compilers do not treat the arrays same way as do C (i.e C99) compilers.
However, other version of C (i.e C89) doesn't support VLA. So C89 arrays would be [almost] same as C++ arrays.
Yes, they are treated in the same way. However, in C++ you probably should not be using them - investigate the std::vector
class!
Yes. Arrays are treated in the same way in C and C++. However, C++ now has the STL
, which is a collection of data structures and operations on them, such as string, vector, deque etc.
Yes, C++ is an extended version of C language apart from its interesting and appealing OOP features. Strostrupp and other designed it with sole intention of creating a Object Oriented Language with C like syntax. Fundamentally both are same in most cases (excluding C++'s OOP features) and arrays are not an exception.
"An array is basically a pointer to a sequential memory block. where the name of the array represents the first location of that block." This statement is true for both C and C++.
Array Implementation is same though there are some restrictions in how C++ compilers allow you to use them.
精彩评论