C ++ How to warn about the difference between argument names in function declaration and definition

Is there a way to get a warning about missing argument names between a function declaration and its definition?

Statement

double divide(int a, int b); 

Definition

 double divide(int b, int a) { return a / b; } 

For a user using the divide function, the result is expected a / b, not b / a.

I know the compiler cannot do this, but are there any static analysis tools that can do this? If so, which ones?

+5
source share
3 answers

You can use clang-tidy. The call to this compiler is a little stretched, but perhaps it is possible to do clang emit clang-tidy warnings. The specific option you want is readability-inconsistent-declaration-parameter-name .

+10
source

The compiler does not need the argument names in your declaration, you can even write void foo(int, int); therefore there is no discrepancy, and there is no such warning. If for some reason you find this inconsistency confusing, just omit the argument names in the declarations.

0
source

Are you just interested in checking the existing code or want to make sure that the code avoids this problem and are ready to reverse engineer the interfaces?

In the latter case:

If you have many arguments of the same type, then inconsistencies can be a problem (and I saw worse than your example):

 void foo(bool fast, bool small, bool trivial); foo(true, false, false); 

What you're asking for is a way to ensure consistency between the declaration and the definition of foo, but you ignore the inconsistencies between the call and the declaration.

Another solution is to instead create an argument structure using setRoutines. Sort of:

 struct FooArg { bool fast, small, trivial; FooArg &setFast(bool fast_) {fast=fast_;return *this;}; ... }; void foo(FooArg const&); foo(FooArg().setFast(true).setSmall(false)...); 

Then you avoid inconsistencies between declaration, definition and invocation, but should be more detailed. (I'm sure there is some kind of answer about this technique.)

0
source

Source: https://habr.com/ru/post/1259271/


All Articles