Issue 179064
Summary clang-tidy check proposal: suggest-missing-const
Labels clang-tidy
Assignees
Reporter Saint-Martin
    ## 1. Introduction

The `const` keyword greatly improves the readability and correctness of C++ software: it clarifies APIs, helps static analysis, and prevents accidental modifications (Scott Meyers, *Effective C++*: “use const whenever possible”).

However, developers may sometimes not see, or forget to mark, a variable or a member function as `const` even when it could be.

A static analysis tool, such as clang-tidy, could help by detecting these missed opportunities.

## 2. Motivation

Help the programmer identify variables and functions that could safely be declared `const`.

## 3. Problem Description

Examples of missing `const`:

- A local variable is never written after initialization  
  `int a = 3;`

- A parameter is not modified and could be `const`  
  `int f(const int& n) { int m = n; return 0; }`

- A member function does not modify any member and could be `const`  
  ``
  struct A {
  int x;
  void f() { std::cout << x; } // could be const
  };
  ``

- A global variable is never written after initialization

## 4. Proposed Solution

clang-tidy could detect these missing `const` qualifiers and warn the programmer.

### 4.1 Heuristic

1. **Missing const variable**  
   The variable is not written to after initialization within its scope.

2. **Missing const method**  
   
   - The method does not write to any non-mutable member  
   - The method only calls other `const` methods  
   - (This heuristic does not consider global state or side effects.)

### 4.2 Limitations

- Does not detect transitive writes through pointers or references  
- Does not consider global state  
- Does not infer logical constness  

## 5. Examples

### Example 1 — Detecting variables that could have been const

```
 #include <iostream>

int main() {
int term = 2; // should emit: "variable 'term' could be declared const"
int tab[] = {0, 1, 2};
for (int i = 0; i != 3; ++i) {
int x = i + term;
}
return 0;
}
```

### Example 2 — Detecting member functions that could have been const

```
#include <iostream>
class B {
public:
void write() const {
std::cout << "B writing" << std::endl;
}
};

class A {
B b;
public:
void write() { // write could have been const
b.write();
}
};
```

## 6. Impact

Improves readability, maintainability, and debugging clarity.

## 7. Conclusion

Feedback and suggestions are welcome and appreciated.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to