c - 在 C 中将函数参数声明为 const
问题描述
在 C 中将函数的参数声明为 const 有什么用?它对性能有影响吗?
例如,为什么您更喜欢 f1 而不是 f2?还是 f2 到 f1?
void f1(const char* arg) {
/* some code */
}
void f2(char* arg) {
/* some code */
}
解决方案
in void f1(const char *arg)
the argument arg
itself is not const
qualified, it is defined as a pointer to an array of char
that the function should not modify. This is very useful for the reader to understand at first glance that the function f1
does not modify the string it receives.
For example strcpy
is declared in <string.h>
as:
char *strcpy(char *dest, const char *src);
The array pointed to by the first argument is modified, it is the destination array, the second argument points to the source array, which is not modified.
This type of const
qualification is viral: once you define an argument as pointing to a const
object, you can only pass it to functions that have similarly const
qualified arguments.
Regarding the impact on performance, there is no downside. Some compilers might even benefit from this qualifications and generate better code.
So in your example, if f1
does not modify the array pointed to by arg
, unless you need to store f1
in a function pointer of type void (*)(char*)
and cannot change this type, I strongly advise to use:
void f1(const char *arg);
推荐阅读
- mysql - 根据一列中的值按组计算百分比
- swift - 映射 Swift 结合未来到另一个未来
- c++ - 函数返回时的 Cpp 调试断言错误
- javascript - 如何在adobe livecycle中拆分字符串并用该字符串内的值填充动态表?
- reactjs - react route如何导入本地scss文件只适用于一个js文件?
- c++ - 输入文件格式无法识别(c++)
- javascript - 如何将此 while 循环转换为 for 循环?
- tcl - 是否有一种解决方法可以在不使用 args 的情况下传递可变数量的参数
- excel - 有没有办法在 Excel 数据透视表中切换使用切片器(或下拉菜单)计算的字段?
- json - 如何修改返回的json