I'm writing a function dealing with string in C, which is recursive. Basically what it does is to find a string between some characters and '\0'
. If before it finds '\0'
, it hits on the particular characters, it will recursively call itself.
When writing it in CLion, I see a warning from Clang-Tidy, which I never saw before. It says
Clang-Tidy: Function 'function' is within a recursive call chain
I'm wondering is it a new feature of CLion 20.02 (I recently updated it)? Moreover, how can I fix it?
Here's my code.
char *function(char *pos, <some arguments>) {
char *temp = pos + 1;
while (1) {
if (*temp == '\0') {
return temp;
} else if (*temp == '<something>') {
*temp = '\0';
if (*(temp + 1) == '\0') {
return function(temp + 1, <some arguments>);
} else if (*(temp + 1) == '<something>') {
if (*(temp + 2) == '\0') {
return function(temp + 2, <some arguments>);
} else {
return function(temp + 1, <some arguments>);
}
} else {
return function(temp, <some arguments>);
}
}
temp++;
}
}
Yes, recent Clang-Tidy diagnoses recursion. If you are intentionally writing a recursive function, and you are confident that it cannot be used in a context where recursion is disallowed (see references in the Clang-Tidy docs, for example), then it is reasonable to ignore that warning. Since "disallowed" is much more often a policy question than a technical one, you should consider clearly documenting that the function is recursive. And you should consider not using recursion, which is generally better for real-world code.
This check was not in Clang-Tidy 10. I'm having trouble finding docs for Clang-Tidy 11, but the release notes for Clang-Tidy 12 do not list it as new, so it looks like it was added in 11.