do not declare C-style arrays, use std::array<> instead
23 Derived(const Derived &other) {}
24};
25
26float foo(float a[100]) {27 // Possible loss of precision due the type-folding from `float` to `int`".
28 // Replace last argument with 0.0
29 return std::accumulate(a, a + 99, 0);
Description
Arrays declared using C-style syntax can lead to problems such as buffer overflows, memory leaks, and undefined behavior. Using std::array
or std::vector
provides better memory management and avoids these issues.
To fix this issue, replace the C-style array declaration with std::array
or std::vector
, depending on the requirements of the code.
Additionally, using std::array
or std::vector
provides a more consistent and idiomatic C++ code style, making the code easier to read and maintain.
Bad practice
void foo() {
int arr[5] = {1, 2, 3, 4, 5};
// ...
}
Recommended
#include <array>
void foo() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
// ...
}
or
#include <vector>
void foo() {
std::vector<int> arr = {1, 2, 3, 4, 5};
// ...
}
For more information, refer to this link.