<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/148739>148739</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[clang-tidy] New check: Use if-initializer to reduce scope of a variable
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang-tidy,
check-request
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
SunBlack
</td>
</tr>
</table>
<pre>
Over the years, we have accumulated a lot of codes like this one:
```cpp
const auto it = myMap.find(value);
if (it != myMap.end())
{
// do sth with the iterator
}
```
Since C++17 there are if-initializers that make it easier to see whether the variable is only needed in one block or whether it will be needed again later.
So you can write sth. like this:
```cpp
if (const auto it = myMap.find(value);
it != myMap.end())
{
// do sth with the iterator
}
```
Maybe this could also be part of a bigger check to reduce the variable scope in general (similar to to the `variableScope` check in Cppcheck).
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJy0k82OozgQx5_GXEpBxEAgBw75UG69e2jtA5TtCtTGwaxtEmWffmSSnu4ZzWUOIyFhWf_6-P-qjCFwPxJ1ot6L-pjhHAfnu_d53FvUl0w58-j-vpGHOBA8CH0Q8gB3ggFvBKj1fJ0tRjKAYF0EdwbtDAWwfCGIAwdwI4lyJ4qd2BTPT0-TKHbajSECztEBRxDlEa6PN5zyM49GyPaGdiYht6Lci2LHZxCyTTq5_pTSokwiuU0FmiQFEPIk5AmMgxAHuHMclvY5ksfo_KI8fm0onYvdO4-a4CDkXsj9ukkxngA9AZ9XPHJktPw_-QBxwAhXvKScQBg4AXIQiOA-UIpbCt7QMypLsFCwDxiJDBngMUEBZZ2-gPPfYzjCna0FRR9K7JFHSIB9_mrSwcPNoHGEu-dIyWL-SfuXpJ_wfos3AMCfpf2GD_XaEO1mawBtcMn6hH7ZIwTFfU8e9ED6kvh6MrOmH9EG7SZKRHsayaNNTgNf2eIykvQNBGJTfES8pwCxKV5peYTDNC1nIbd5ZrrSbMstZtStm1rW5bretNnQmXNbqKY0bUlFVSpTVLqms1K1LFVVNTrjThayLpp1JeV6K9tcUSNV2RrSbVuYzVlUBV2RbW7t7Zo732ccwkzdumqbcptZVGTD8hCl1BbHfhXZPISUQh7SVWpx5em_mUJMt_Ux813KtVJzH0RVWA4xfGaPHO3ysL8kq4_wF92f1kW5g3_Cz8v9hfMT7TKJD3jZ7G03xDgti7YMvuc4zCrX7irkKRV__VaTd_-SjkKeFp9ByNPL6q2T3wIAAP__VJ1rlw">