3

Clang tidy can't detect dead code when I use a lambda function; but, if I replace the lambda with a normal function, Clang tidy pin-points the error like the message below:

warning GC1A2668F: Value stored to 'ret' is never read [clang-analyzer-deadcode.DeadStores]

Is there any way to enforce clang tidy to check dead code even in a lambda function?

Here is my code.(waring: code is meaningless and just for dead code testing). You can use the USE_LAMBDA define in order to switch back and forth between lambda and normal function.

#include <iostream>
#include <algorithm>

using namespace std;

int GetRet()
{
    return 5;
}

#define USE_LAMBDA 1

#if USE_LAMBDA
int main()
{
    int ary[10]{};

    for_each(begin(ary), end(ary), [](int a)
    {
            int ret = GetRet();

            if (a > 5 && ret < 1)
            {
                ret = 6;
            }
    });
    
    return 0;
}

#else

void Check(int a)
{
    int ret = GetRet();

    if (a > 5 && ret < 1)
    {
        ret = 6;
    }
}

int main()
{
    int ary[10]{};

    for_each(begin(ary), end(ary), Check);

    return 0;
}
#endif
Gary Kim
  • 31
  • 3
  • 1
    When I run your code through the clang-cl static analyser (in Visual Studio 2022), I get a slightly different warning when using the lambda: *warning G183B9D1E: variable 'ret' set but not used [clang-diagnostic-unused-but-set-variable]* (on the `int ret = GetRet();` line). – Adrian Mole Jul 02 '22 at 12:51
  • Clang tidy is not perfect. There are more cases it e.g. gives false positives – JHBonarius Jul 02 '22 at 12:57
  • @AdrianMole Thank you . I used VS 2019. As you recommended, I tried VS 2022 and it works like a charm. – Gary Kim Jul 05 '22 at 08:28
  • @AdrianMole If I change the conditional code to (a > 5 && ret < 1),It cannot still detect the dead code. – Gary Kim Jul 05 '22 at 09:20

0 Answers0