Skip to content

[clang-tidy] New check: Use if-initializer to reduce scope of a variable #148739

Closed as duplicate of#38471
@SunBlack

Description

@SunBlack

Over the years, we have accumulated a lot of codes like this one:

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:

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions