This is similar to (but different from) this question.
Here is some simple test code to illustrate some weirdness I have discovered with Sun CC:
//--
See C++ Coding Standards by Alexandrescu #15. This should work according to him. The const prevents the implementer of the function from changing the input variable. IMO the variable should remain const inside the function. If you need a variable, declare one. The optimizer will get rid of it for you.
int temp = a;
Since this does not work here I am advising my class to use the (const int a) in both the prototype and implementation. I am a big fan of using techniques that work for all compilers.
This looks like a compiler problem in CC
. The C++ standard says (in 13.1 Overloadable declarations):
Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called.
But there are const
/volatile
modifiers that can participate in overloading, as the standard mentions shortly afterwards:
Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.
My understanding is that this is allowed because it makes little difference for the caller. It is not the function that is const, but rather a parameter, and you are making the addition in the definition. Thus, the const you actually added affects only the implementation
See this question.
The const
is void func1(const int)
has no affect whatsoever on the function, since the int is passed by value --- a copy of the int is made, and that copy lives only as long as the function call. Whether or not you change that copy has no bearing on anything.
You are probably confused by the fact that in void func2(const char*)
the const
is significant. But you have to recognized that is different from void func3(char* const)
. In the former, it's the character pointed to that cannot change; in the latter, it's the pointer that is (irrelevantly) 'const'
Yes, a const int is not the same as an int.
I would always match the const
on both declaration and definition. This would reduce any problems because the signatures would match then.