Quick question:
int testfunc1 (const int a)
{
return a;
}
int testfunc2 (int const a)
{
return a;
}
Are these two functions the same in every aspect or is there a difference? I'm interested in an answer for the C-language, but if there is something interesting in the C++ language, I'd like to know as well.
This isn't a direct answer but a related tip. To keep things straight, I always use the convection "put
const
on the outside", where by "outside" I mean the far left or far right. That way there is no confusion -- the const applies to the closest thing (either the type or the*
). E.g.,The trick is to read the declaration backwards (right-to-left):
Both are the same thing. Therefore:
The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:
They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions must be declared this way:
It changes the
this
pointer in the function fromFoo * const
toFoo const * const
. See here.