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

Jason Wilkins jason.a.wilkins at gmail.com
Sun Oct 7 11:25:29 CEST 2012


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 :)


More information about the Bf-committers mailing list