Declaring a pointer to const or a const pointer to const as a formal parameter

北城余情 提交于 2019-12-05 07:52:16

What are the advantages of declaring a pointer as a const - as a formal parameter? I know that I can do it, but why would I want to... particularly in the case where the pointer being passed and the data it is pointing to are not declared constant?

I assumed you meant a pointer to const.

By have a pointer to const as a parameter, the advantage is you document the API by telling the programmer your function does not modify the object pointed by the pointer.

For example look at memcpy prototype:

void *memcpy(void * restrict s1, const void * restrict s2, size_t n);

It tells the programmer the object pointed to by s2 will not be modified through memcpy call.

It also provides compiler enforced documentation as the implementation will issue a diagnostic if you modify a pointee from a pointer to const.

const also allows to indicate users of your function that you won't modify this parameter behind their back

If you declare a formal parameter as const, the compiler can check that your code does not attempt to modify that parameter, yielding better software quality.

Const correctness is a wonderful thing. For one, it lets the compiler help keep you from making mistakes. An obvious simple case is assigning when you meant to compare. In that instance, if the pointer is const, the compiler will give you an error. Google 'const correctness' and you'll find many resources on the benefits of it.

Pavan Manjunath

For your first question, if you are damn sure of not modifying either the pointer or the variable it points to, you can by all means go ahead and make both of them constant!

Now, for your Qn as to why declare a formal pointer parameter as const even though the passed pointer is not constant, A typical use case is library function printf(). printf is supposed to accept const char * but the compiler doesn't complain even if you pass a char* to it. In such a case, it makes sense that printf() doesn't not build upon the user's mistake and alter user's data inadvertantly! Its like printf() clearly telling- Whether you pass a const char * or char*, dont worry, I still wont modify your data!

For your second question, const pointers find excellent application in the embedded world where we generally write to a memory address directly. Here is the detailed explanation

Well, what are the advantages of declaring anything as a const while you have the option to not to do so? After all, if you don't touch it, it doesn't matter if it's const or not. This provides some safety checks that the compiler can do for you, and it gives some information of the function interface. For example, you can safely pass a string literal to a function that expects a const char *, but you need to be careful if the parameter is declared as just a char *.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!