Skip to content

Commit 3912ba8

Browse files
committed
recommend std::array for fixed size parameter
1 parent 6566e42 commit 3912ba8

File tree

2 files changed

+17
-11
lines changed

2 files changed

+17
-11
lines changed

clang-tools-extra/clang-tidy/modernize/AvoidCArraysCheck.cpp

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -81,18 +81,20 @@ void AvoidCArraysCheck::registerMatchers(MatchFinder *Finder) {
8181

8282
void AvoidCArraysCheck::check(const MatchFinder::MatchResult &Result) {
8383
const auto *ArrayType = Result.Nodes.getNodeAs<TypeLoc>("typeloc");
84-
bool const IsInParam =
84+
const bool IsInParam =
8585
Result.Nodes.getNodeAs<ParmVarDecl>("param_decl") != nullptr;
8686
const bool IsVLA = ArrayType->getTypePtr()->isVariableArrayType();
87-
// in function parameter, we also don't know the size of IncompleteArrayType.
88-
const bool IsUnknownSize =
89-
IsVLA || (ArrayType->getTypePtr()->isIncompleteArrayType() && IsInParam);
9087
enum class RecommendType { Array, Vector, Span };
91-
const RecommendType RecommendType =
92-
(IsInParam && Result.Context->getLangOpts().CPlusPlus20)
93-
? RecommendType::Span
94-
: IsUnknownSize ? RecommendType::Vector
95-
: RecommendType::Array;
88+
RecommendType RecommendType = RecommendType::Array;
89+
if (IsVLA) {
90+
RecommendType = RecommendType::Vector;
91+
} else if (ArrayType->getTypePtr()->isIncompleteArrayType() && IsInParam) {
92+
// in function parameter, we also don't know the size of
93+
// IncompleteArrayType.
94+
RecommendType = Result.Context->getLangOpts().CPlusPlus20
95+
? RecommendType::Span
96+
: RecommendType::Vector;
97+
}
9698
diag(ArrayType->getBeginLoc(),
9799
"do not declare %select{C-style|C VLA}0 arrays, use "
98100
"%select{std::array<>|std::vector<>|std::span<>}1 instead")
Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
// RUN: %check_clang_tidy -std=c++20 %s modernize-avoid-c-arrays %t
22

3-
int foo(int data[], int size) {
4-
// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: do not declare C-style arrays, use std::span<> instead
3+
int f1(int data[], int size) {
4+
// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: do not declare C-style arrays, use std::span<> instead
55
int f4[] = {1, 2};
66
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not declare C-style arrays, use std::array<> instead
77
}
8+
9+
int f2(int data[100]) {
10+
// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: do not declare C-style arrays, use std::array<> instead
11+
}

0 commit comments

Comments
 (0)