Search code examples
c++parametersconstantsfunction-declarationconst-correctness

Does using const on function parameters have any effect? Why does it not affect the function signature?


For example, imagine a simple mutator that takes a single boolean parameter:

void SetValue(const bool b) { my_val_ = b; }

Does that const actually have any impact? Personally I opt to use it extensively, including parameters, but in this case I wonder if it makes any difference.

I was also surprised to learn that you can omit const from parameters in a function declaration but can include it in the function definition, e.g.:

.h file

void func(int n, long l);

.cpp file

void func(const int n, const long l) { /* ... */ }

Is there a reason for this? It seems a little unusual to me.


Solution

  • The reason is that const for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though.

    I personally tend to not use const except for reference and pointer parameters. For copied objects it doesn't really matter, although it can be safer as it signals intent within the function. It's really a judgement call. I do tend to use const_iterator though when looping on something and I don't intend on modifying it, so I guess to each his own, as long as const correctness for reference types is rigorously maintained.