首页 > 解决方案 > Adding /*const*/ instead of const qualifier to char * param in function prototype

问题描述

I am facing a function which takes a pointer to a char array but it performs only read operations on the mem the char * points to.

I could add const to the prototype directly before the char * parameter, but this would break the rest of the non const-correct code. I decided to add a comment /*const*/ instead to indicate that the function performs only read operations.

However, this confuses my colleagues and I wonder if adding the comments is a common approach and the criticism is unjustified.

Example:

int func(const char *readat);

versus

int func(/*const*/ char *readat);

标签: cfunctionconstantsconst-correctness

解决方案


添加const到函数参数不会破坏任何调用代码。允许将非常量对象分配给 const 对象。

所以这是允许的:

char c;
char *p = &c;
const char *cp = p;

但这不是:

char c;
const char *cp = &c;
char *p = cp;

推荐阅读