V761. NN identical blocks were found.


The analyzer detected code that could be refactored. This diagnostic looks for three or more identical code blocks. Such repeated code is unlikely to be incorrect, but it is better to factor it out in a separate function.

If your code employs a lot of local variables, use lambda functions to capture data by reference.

This diagnostic can be triggered multiple times by code that uses numerous manual optimizations (for example manual loop unrolling). If you find the V761 diagnostic irrelevant to your project, turn it off.

Consider the following synthetic example:

void process(char *&buf);

void func(size_t n, char *arr)
{
    size_t i;

    i = n;
    while (i--)
        arr[i] = 1;
    for (i = 0; i != 10; i++)
        arr[i] = 'a';
    process(arr);

    i = n;
    while (i--)
        arr[i] = 1;
    for (i = 0; i != 10; i++)
        arr[i] = 'a';
    process(arr);

    i = n;
    while (i--)
        arr[i] = 1;
    for (i = 0; i != 10; i++)
        arr[i] = 'a';
    process(arr);

    i = n;
    while (i--)
        arr[i] = 1;
    for (i = 0; i != 10; i++)
        arr[i] = 'a';
    process(arr);
}

It is a good solution to factor out the common code in a separate function:

void process(char*& buf);

void func_impl(size_t i, size_t *&arr)
{
    while (i--)
        arr[i] = 1;
    for (i = 0; i != 10; i++)
        arr[i] = 'a';
    process(arr);
}

void func(size_t n, char *arr)
{
    for (size_t i = 0; i < 4; ++i)
        func_impl(n, arr);
}

See also diagnostic V760.


Bugs Found

Checked Projects
334
Collected Errors
12 668