| 1 |
// RUN: %check_clang_tidy %s cppcoreguidelines-pro-bounds-array-to-pointer-decay %t |
| 2 |
#include <stddef.h> |
| 3 |
|
| 4 |
namespace gsl { |
| 5 |
template <class T> |
| 6 |
class array_view { |
| 7 |
public: |
| 8 |
template <class U, size_t N> |
| 9 |
array_view(U (&arr)[N]); |
| 10 |
}; |
| 11 |
} |
| 12 |
|
| 13 |
void pointerfun(int *p); |
| 14 |
void arrayfun(int p[]); |
| 15 |
void arrayviewfun(gsl::array_view<int> &p); |
| 16 |
size_t s(); |
| 17 |
|
| 18 |
void f() { |
| 19 |
int a[5]; |
| 20 |
pointerfun(a); |
| 21 |
// CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not implicitly decay an array into a pointer; consider using gsl::array_view or an explicit cast instead [cppcoreguidelines-pro-bounds-array-to-pointer-decay] |
| 22 |
pointerfun((int *)a); // OK, explicit cast |
| 23 |
arrayfun(a); |
| 24 |
// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not implicitly decay an array into a pointer |
| 25 |
|
| 26 |
pointerfun(a + s() - 10); // Convert to &a[g() - 10]; |
| 27 |
// CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not implicitly decay an array into a pointer |
| 28 |
|
| 29 |
gsl::array_view<int> av(a); |
| 30 |
arrayviewfun(av); // OK |
| 31 |
|
| 32 |
int i = a[0]; // OK |
| 33 |
int j = a[(1 + 2)];// OK |
| 34 |
pointerfun(&a[0]); // OK |
| 35 |
|
| 36 |
for (auto &e : a) // OK, iteration internally decays array to pointer |
| 37 |
e = 1; |
| 38 |
} |
| 39 |
|
| 40 |
const char *g() { |
| 41 |
return "clang"; // OK, decay string literal to pointer |
| 42 |
} |
| 43 |
const char *g2() { |
| 44 |
return ("clang"); // OK, ParenExpr hides the literal-pointer decay |
| 45 |
} |
| 46 |
const char *g3() { |
| 47 |
return __func__; // OK, don't diagnose PredefinedExpr |
| 48 |
} |
| 49 |
|
| 50 |
void f2(void *const *); |
| 51 |
void bug25362() { |
| 52 |
void *a[2]; |
| 53 |
f2(static_cast<void *const*>(a)); // OK, explicit cast |
| 54 |
} |
| 55 |
|
| 56 |
void issue31155(int i) { |
| 57 |
const char *a = i ? "foo" : "bar"; // OK, decay string literal to pointer |
| 58 |
const char *b = i ? "foo" : "foobar"; // OK, decay string literal to pointer |
| 59 |
|
| 60 |
char arr[1]; |
| 61 |
const char *c = i ? arr : "bar"; |
| 62 |
// CHECK-MESSAGES: :[[@LINE-1]]:23: warning: do not implicitly decay an array into a pointer |
| 63 |
const char *d = i ? "foo" : arr; |
| 64 |
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: do not implicitly decay an array into a pointer |
| 65 |
} |