[Bf-committers] Using 'const' on primitive function arguments passed by value (Please don't do this)

Campbell Barton ideasman42 at gmail.com
Sun Oct 7 15:22:16 CEST 2012

On Sun, Oct 7, 2012 at 8:25 PM, Jason Wilkins <jason.a.wilkins at gmail.com> wrote:
> If I had a function with the prototype: foo(int bar)
> It may be tempting to declare the it as: foo(const int bar)
> The reason would be that bar is not modified inside of foo, so by
> declaring it this way we prevent ourselves from accidentally modifying
> it.
> This is not idiomatic C, and for good reasons.
> 1) We use 'const' on pointers to indicate that we are not going to
> modify what is pointed at, when a programmer sees 'const int' it is
> momentarily confusing because we expect 'const int*'
> 2) This exposes internal details of the function to the outside world.
>  The fact that 'bar' is const in this case is not actually a part of
> the interface of that function.
> 3) If we change our minds later and actually do want to modify the
> copy of 'bar' inside the function then we have to change the interface
> again, but as per #2 it actually has nothing to do with the user of
> 'foo'
> 4) It is just not idiomatic.  Looking at it is like listening to a
> foreigner speak your native language in "creative" ways.
> I have not figured out who is doing this, but please stop :)

I've been doing this and Im not convinced its a bad thing, in some
functions its a good hint that a var is `fixed` and shouldn't be
If a dev wants to change it they can just remove the `const` but it
means they think twice before doing it (as in - maybe there is a good
reason it shouldn't be changed).

The main reason I like to have this sometimes is when debugging you
know for sure a var wont change, if it does - its a buffer overflow or
something exceptional.
Often its not really an issue - but there are cases it can help verify
whats going on when reading the function.

That the `const` gets in the header is a little inconvenience if it
changes often - but IMHO changing those is rare enough that its not an

More information about the Bf-committers mailing list