0

I have read many answers on stackoverflow and codereview that says we should not use C style arrays with C++. What is reason for it ? If I use std::Array instead of C style array, will it impact on speed/performance ?

In my organization, entire application is written in C++. But only C style arrays are used.

5
  • 1
    Theoretically there's no penalty using std::array over a C-style array, and practically I doubt it as well (as long as you don't pass the array by value, which is possible with std::array but not with a C-style array). Commented Sep 23, 2019 at 11:36
  • 4
    Glad to see my gold "arrays" badge getting some use 🤪 Commented Sep 23, 2019 at 11:37
  • @Someprogrammerdude In C I can create variable length array at runtime like int arr[n]. Is it possible with std::array ? Commented Sep 23, 2019 at 11:41
  • @KamalPancholi VLAs are not allowed in standard C++. Commented Sep 23, 2019 at 11:44
  • @KamalPancholi For that you have std::vector. Commented Sep 23, 2019 at 11:47

1 Answer 1

2

No, it will not have impact on performance. There are two reasons to use std::array instead C-like arrays:

  • Method at() that allows to get an element by index with bounds checking. Beware, operator [] doesn't have bounds checking.
  • Limited pointer arithmetic. It's much harder to shoot in the foot than with C-like arrays.
  • Same behavior as other std containers, like begin(), end(), size() methods without necessity to handle two variables: pointer and size. So, you can implement one algorithm that can work with arrays and other containers.

Thanks Thomas Sablik for clarification in comments.

Sign up to request clarification or add additional context in comments.

1 Comment

@ThomasSablik Yes, but the problem with simple C-style arrays is that they too often decay to pointers, and then std::begin() and std::end() won't work very well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.