0

My specific problem is that cppcoreguidelines-avoid-magic-numbers is flagging calls to setters. For example:

auto person = Person();
person.set_height(6); // <--- Flagged as "magic number"

This really isn't a magic number, as the context for what the number represents is made explicit by the setter call itself (it's a Person's height in this case). So I'd like to be able to ignore the cppcoreguidelines-avoid-magic-numbers for all calls to set_height.

What I'd like to be able to do in general is ignore <list-of-warnings> on all invocations of <some-function>, and only ignore on those function invocations (e.g. disabling globally is not desired).

As a workaround, I could write an emacs save hook to go insert // NOLINT(cppcoreguidlines-avoid-magic-numbers) after every line that matches these setters. I'd really rather not do that.

Is this possible to do in an easier way? Are there other workarounds that handle this issue?

Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52

1 Answers1

0
person.set_height(6);

What does it set, inches, feet, cm, meters? The warning is correct, 6 is a magic number even in the context of the height value.

The C++ core guideline suggests that you use user defined literals.

constexpr double operator"" _ft(double height) {
  return height;
}

constexpr double operator"" _in(double height) {
  return height / 12;
}

person.set_height(6_ft);
person.set_height(72_in);
273K
  • 29,503
  • 10
  • 41
  • 64
  • `Person` was just a (too) simple example to illustrate the point. I am looking for a general solution w.r.t `clang-tidy`, and furthermore most of the setters I have are unitless. I appreciate the workaround but it doesn't really answer the question. There's other generic issues I'm trying to address too w/ `clang-tidy` (like some implicit conversions that are fine on certain members but not others) – Matt Messersmith Jan 09 '23 at 17:56
  • Even a unitless value is still a magic number. Use `constexpr int kDefultValue = 6; // comment explaining the chosen value` `obj.set_value(kDefultValue);` – 273K Jan 09 '23 at 18:10
  • I understand _why_ it's happening, and there are workarounds like what you're posting. I don't really want to split one line that's perfectly readable into two lines for the sake of a linter. If the units bother you so much, pretend the function is `set_height_in_feet(...)`. As stated before, there are also other issues that are _unrelated_ to magic numbers w/ `clang-tidy`. That's why I am asking how to make `clang-tidy` ignore it, and not really for introducing units or other utility functions. I appreciate your efforts but this is not what I am looking for and not an answer to the question – Matt Messersmith Jan 09 '23 at 18:29
  • What you want is not supported by clang-tidy. You have to use `// NOLINT(cppcoreguidlines-avoid-magic-numbers)`, it also *splits one line that's perfectly readable into two lines for the sake of a linter* – 273K Jan 09 '23 at 18:32