Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arrays in C++ same as C?

Tags:

c++

arrays

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 interpreted as a pointer.
  • In function argument, array declarations are treated as pointer to start of element.
like image 647
user744621 Avatar asked May 11 '11 06:05

user744621


1 Answers

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.

like image 127
jalf Avatar answered Oct 13 '22 19:10

jalf