首页 > 解决方案 > 在 C 中将函数参数声明为 const

问题描述

在 C 中将函数的参数声明为 const 有什么用?它对性能有影响吗?

例如,为什么您更喜欢 f1 而不是 f2?还是 f2 到 f1?

void f1(const char* arg) {
/* some code */
}

void f2(char* arg) {
/* some code */
}

标签: cconstants

解决方案


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);

推荐阅读