Creating a function parameter char const?

Consider this function declaration:

int IndexOf(const char *, char);

where char * is the string and char is the character to search inside the string (returns -1 if char is not found, otherwise its position). Does it make sense to char as well const? I always try to use constants on pointer parameters, but when something is called by value, I usually leave const.

What are your thoughts?

+5
source share
9 answers

Assuming you are not going to change the value of any parameter:

I would have a function definition as:

int IndexOf( const char * const , const char )
{
    //...
}

But save the function declaration as:

int IndexOf( const char * , char );

:
const , const .

?

  • const , ( const, ).
  • .
  • , .
  • .

pass-on-value const " " - , .

, , , const .

+4

, , .

, , , , .

:

void foo (int count) {
  while (count--) {
    do_something();
  }
}

, , , const, , , . , const, .

+4

, char const. , , , ? , const .

+4

, , , , const .

, -POD-, . , , , const , / - .

" const, , const"

+3

, , char , .

+2

, .

, . .

. , , .

, "make it const" , -, . , , , const. , , , , , . , , , . , .

, . const, . , , .

+2

3- , const .

300- , , 289, .

+1

Pro const:

Contra const:

  • Changes to the implementation (i.e. the removal of the classifier) ​​will change the interface

The ideal solution is to provide constonly in the declaration, which is part of the function definition. However, the C standard does not allow this; it will work as expected in all reasonable implementations of C. However.

+1
source

I'd say that constnothing has been added to your code.

0
source

All Articles