查看 C 标准库中的大多数函数,似乎缺少 const,通常首选指定 const。
例如:
ctype.h/c
extern int isupper(int __c) __ATTR_CONST__;
extern int islower(int __c) __ATTR_CONST__;
extern int isdigit(int __c) __ATTR_CONST__;
为什么不是这些:
extern int isupper(const int __c) __ATTR_CONST__;
extern int islower(const int __c) __ATTR_CONST__;
extern int isdigit(const int __c) __ATTR_CONST__;
他们毕竟只观察参数:
int isupper(int c) {
return _pctype[c] & _UPPER;
}
int islower(int c) {
return _pctype[c] & _LOWER;
}
int isdigit(int c) {
return _pctype[c] & _DIGIT;
}
或者让我们在 string.c 中使用一个函数:
void *memcpy(void *dest, const void *src, size_t count)
{
char *tmp = dest;
const char *s = src;
while (count--)
*tmp++ = *s++;
return dest;
}
为什么不:
void *memcpy(void *const dest, const void *const src, size_t count);
const 被排除在这些地方是有原因的吗?
以我所展示的方式包含 const 会是错误的吗?
我认为由于历史原因,这些功能一直保持这种状态,
但我想我应该问一下,以防我错过了什么。
那些是
const
-正确的签名。
你几乎不会在传值参数之前写
const
。
该函数有自己的副本,因此不会有危险。
函数的实现可以向自己承诺不修改参数
int isupper(const int c){ ... }
,并且编译器将强制执行它以帮助实现其逻辑,但是顶级限定符不是函数签名的一部分,并且它与 int isupper(int);
完全兼容(也适用于顶级 volatile
和 restrict
)。
int isupper(int);
int isupper(int const);
//fully compatible prototype -- top level qualifiers are not
//part of the function signature
void *memcpy(void *dest, const void *src, size_t count)
也是 const
- 正确。只有第二个指针承诺不会改变它所指向的内容。另一方面,目标指针的作用就是改变它所指向的内容。