Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a char function parameter const?

Tags:

c++

c

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?

like image 524
helpermethod Avatar asked Dec 21 '10 13:12

helpermethod


People also ask

Can a char * be passed as const * argument?

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 ...

What is a char * const?

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.

What is a const parameter?

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.


1 Answers

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?

  1. Seperating the header and implimentation allows me to change the parameters that are const in the implimentation without ever touching the header (except those that are vitally const, which should require a header change).
  2. It's makes the code more self-documenting.
  3. It makes it harder to introduce bugs without the compiler catching them as errors.
  4. It makes it harder for other programmers to introduce bugs when making future changes.

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.

like image 96
DMA57361 Avatar answered Sep 21 '22 15:09

DMA57361