3
struct Foo {
    void foo(const int);
};
void Foo::foo(int a) { // 1: This compiles
    a = 0; // 2: This compiles
}

struct Bar {
    void bar(int);
};
void Bar::bar(const int a) { // 3: This compiles
    // a = 0; 4: This would be a compiler error
}

int main() { return 0; }

I would have expected 1 and 3 to be compiler errors but they are not

I suppose that because 1 compiles 2 is considered to be "ok" because it doesn't affect the caller (this is a guess)

4 does not compile which is good

Using gcc 9.3.1 if it matters, curious to know if this can be made into a warning

asimes
  • 5,749
  • 5
  • 39
  • 76
  • Usually it's done the other way around, where the declaration is `int`, but the definition the parameter is `const`. (As in the Bar case.) The `const` is not part of the signature for this kind of use-case, which is why it is not an error. The `const` pass-by-value parameter is useful to catch yourself from making an unintentional mistake -- but it's mostly a *team policy* kind of discipline. The pass-by-value parameters are local to the routine, and the value is seated by the caller. – Eljay Feb 26 '21 at 19:43
  • Note that you can get a warning for `const` in the header file with clang-tidy: https://godbolt.org/z/7c8abs . Not quite the kind of warning you were looking for, but it may be helpful – Justin Feb 26 '21 at 19:48

0 Answers0