llvm / llvm/llvm-project

[clang-tidy] cppcoreguidelines-pro-bounds-constant-array-index is too strict

Open
#207,392 2 comments 1 reaction 0 assignees View on GitHub
clang-tidy enhancement
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

~~~~
if ( index < buffer.size() ) {
return buffer[index];
}
~~~~
(`buffer` is a constant `std::array`, in case it has any relevance)

clang-tidy diagnoses

~~~~
Do not use array subscript when the index is not an integer constant expressionclang-tidy[cppcoreguidelines-pro-bounds-constant-array-index]
~~~~

This is correct, but not really helpful.
One can rewrite the code as

~~~~
if ( index < buffer.size() ) {
return buffer.at(index);
}
~~~~

but I would prefer not to.

In this case, `.at` never fails.
Introducing it where it is not necessary means I cannot use it to distinguish places where I need the safety of it (because the index was not verified) or because I just wanted to silent some linter.

Another alternative would be to suppress the warning locally, but it does not scale well if most indexes are already verified and it is "trivial" to see that they are valid. in case it.

Ideally it would be possible to relax cppcoreguidelines-pro-bounds-constant-array-index.

If for `std::array` `buffer[0]`, `buffer[1]`, `buffer[2]` ... are fine, then `if(i

Contributor guide

Open the contributing guide

Research direction

Start by locating the cppcoreguidelines-pro-bounds-constant-array-index check and its existing tests. Reproduce the reported std::array example, then define coverage for verified and unverified indexes; done means verified dynamic indexes no longer trigger the warning while unsafe accesses still do.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.