我最近正在阅读有关使用const
关键字作为 C 中的函数参数及其使用方法已在何时以及出于什么目的constC语言中变量的关键字 https://softwareengineering.stackexchange.com/questions/204500/when-and-for-what-purposes-should-the-const-keyword-be-used-in-c-for-variables并被接受为正确答案。在这篇文章中,有一点提到
切勿使用const
在函数原型中传递参数
价值。它没有任何意义,因此只是“噪音”。
我用过这种方法,它对我有用,但我不知道为什么这是一个noise对于按值传递的参数,但对于按引用传递的参数来说不是噪音(更恰当的是 C 中的指针值,因为没有pass by value
and pass by reference
在C)中。因此,通过这个解释,当我将指针作为函数参数传递并使用const
关键词;我必须对头文件中的声明和 C 文件中的定义执行此操作,但我不需要使用const
声明(头文件)中非指针参数的关键字,并且仅在 C 文件中定义函数时使用它。
有什么解释吗?
The statement you quote is a bit misleading, because in C, all arguments are passed by value.* I suppose it is trying to distinguish between the arguments themselves and, for the special case of arguments that are pointers, their referents.
无论如何,重点是const
- 在函数声明中限定函数参数不会向调用者传达任何信息。不管这样的限定如何,函数无论如何都不能修改调用者的任何参数的副本,因为参数是按值传递.
*Note, however, that arrays are never passed at all. In function call expressions, as in most contexts, array values "decay" to pointers, and those pointers are passed by value. This produces an effect similar, but not identical, to what you would have if arrays were passed by reference.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)