我最近对代码进行了一些调整,其中我不得不更改函数中的形式参数。最初,该参数类似于以下内容(注意,该结构之前已进行了类型定义):
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)
{
...
}
进行更改是因为我可以在编译时间之前定义和初始化 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)
{
...
}
我还注意到,当我在我的程序上运行 Lint 时,有几个 Info 818 引用了许多不同的函数。该信息指出“指针参数‘x’(第 253 行)可以声明为指向 const”。
关于上述内容,我有两个问题。首先,对于上面的代码,由于指针和 MySpecialStructure 中的变量在函数内都没有改变,那么将指针也声明为常量是否有益?例如-
int myFunction (const MySpecialStructure * const p_structure, unsigned char useful_char)
我的第二个问题是关于 Lint 信息。如果函数不更改其值,那么将指针声明为常量形式参数是否有任何好处或缺点……即使您传递给函数的内容从未被声明为常量?例如-
static unsigned char my_char;
static unsigned char * p_my_char;
p_my_char = &my_char;
int myFunction (const unsigned char * p_char)
{
...
}
感谢您的帮助!
为澄清而编辑 -
声明指向const
的指针或const
指向const
的指针有什么好处- 作为形式参数?我知道我可以做到这一点,但我为什么要...特别是在传递指针和它指向的数据未声明为常量的情况下?
最佳答案
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?
我假设你指的是指向 const
的指针。
通过将指向 const
的指针作为参数,优点是您可以通过告诉程序员您的函数不会修改指针指向的对象来记录 API。
例如看memcpy
原型(prototype):
void *memcpy(void * restrict s1, const void * restrict s2, size_t n);
它告诉程序员s2
指向的对象不会被memcpy
调用修改。
它还提供编译器强制文档,因为如果您将指针对象从指向 const
的指针修改,实现将发出诊断。
关于c - 将指向 const 的指针或指向 const 的 const 指针声明为形式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9419051/