【发布时间】:2019-01-15 13:52:13
【问题描述】:
在 C 中将函数的参数声明为 const 有什么用?它对性能有影响吗?
例如为什么你更喜欢 f1 而不是 f2?还是 f2 到 f1?
void f1(const char* arg) {
/* some code */
}
void f2(char* arg) {
/* some code */
}
【问题讨论】:
-
嗯...作为参数传递的指针可以在函数中修改。所以如果它们被定义为
const,那么它们将永远指向同一个地址……另一个参考:stackoverflow.com/questions/12291607/… -
表示不会修改,看这里:stackoverflow.com/questions/9419051/…
-
@PhoenixBlue 当然是错的。
-
如果
f1()保证不会更改输入arg或其内容,我更喜欢void f1(const char const * arg) -
@PhoenixBlue 请看
const的位置。它不影响指针。