声明指向const的指针或指向const的const指针作为形式参数

emb*_*guy 6 c embedded optimization

我最近对代码做了一些调整,其中我不得不在函数中更改形式参数.最初,参数类似于以下(注意,结构是之前的typedef):

static MySpecialStructure my_special_structure;
static unsigned char char_being_passed;              // Passed to function elsewhere.
static MySpecialStructure * p_my_special_structure;  // Passed to function elsewhere.

int myFunction (MySpecialStructure * p_structure, unsigned char useful_char)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

之所以进行更改,是因为我可以在编译时定义并初始化my_special_structure,而myFunction从未更改过它的值.这导致了以下变化:

static const MySpecialStructure my_special_structure;
static unsigned char char_being_passed;              // Passed to function elsewhere.
static MySpecialStructure * p_my_special_structure;  // Passed to function elsewhere.

int myFunction (const MySpecialStructure * p_structure, unsigned char useful_char)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我还注意到,当我在程序上运行Lint时,有几个Info 818引用了许多不同的功能.该信息表明"指针参数'x'(第253行)可以声明为指向const".

现在,关于上述问题,我有两个问题.首先,关于上面的代码,既然指针和MySpecialStructure中的变量都没有在函数内改变,那么将指针声明为常量也是有益的吗?例如 -

int myFunction (const MySpecialStructure * const p_structure, unsigned char useful_char)
Run Code Online (Sandbox Code Playgroud)

我的第二个问题是关于Lint的信息.如果函数没有改变它的值,将指针声明为常量形式参数是否有任何好处或缺点...即使传递给函数的内容从未被声明为常量?例如 -

static unsigned char my_char;
static unsigned char * p_my_char;
p_my_char = &my_char;

int myFunction (const unsigned char * p_char)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

编辑澄清 -

声明指针constconst指针const的优点是什么- 作为形式参数?我知道我可以做到,但为什么我要......尤其是在传递指针并且指向的数据未声明为常量的情况下?

oua*_*uah 9

将指针声明为const有什么好处 - 作为形式参数?我知道我可以做到,但为什么我要......尤其是在传递指针并且指向的数据未声明为常量的情况下?

我以为你的意思是指向const.

通过指向const作为参数的指针,优点是通过告诉程序员您的函数不修改指针指向的对象来记录API.

例如看memcpy原型:

void *memcpy(void * restrict s1, const void * restrict s2, size_t n);
Run Code Online (Sandbox Code Playgroud)

它告诉程序员指向的对象s2不会通过memcpy调用修改.

它还提供编译器强制文档,因为如果从指针修改指针,实现将发出诊断const.