Consider this function declaration:
int IndexOf(const char *, char);
where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const
? I always try to use const on pointer parameters but when something is called by value, I normally leave the const away.
What are your thoughts?
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
char* const is an immutable pointer (it cannot point to any other location) but the contents of location at which it points are mutable. const char* const is an immutable pointer to an immutable character/string.
Using the const keyword tells the compiler that the value of that parameter will not be changed inside the function. Hence, the compiler can make optimizations that would not have been possible otherwise. A constant parameter cannot be passed as a variable argument to another subroutine.
Assuming you don't intend to adjust the value of either parameter:
I would have the function definition as:
int IndexOf( const char * const , const char )
{
//...
}
But keep the function declaration as:
int IndexOf( const char * , char );
In other words:
I'd reveal the bare minimum level of const
in the header, but then use the maximum possible level of const
in the implimentation.
Why?
const
in the implimentation without ever touching the header (except those that are vitally const
, which should require a header change).Making a pass-by-value paramter const
or not has "no effect" in terms of affecting the caller of the function - which is why you should keep them out the header - but they can make your implimentation more robust and easier to maintain.
Obviously, if it's more useful to change the parameter rather than copying it into another local variable then don't make it const
for the sake of doing so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With