C 标准库中的strchr
函数在字符串中查找char
,但其签名采用int
作为搜索字符.在我发现的这两个实现中,实现将此 int
转换为 char
:
char *strchr(const char *s, int c) {
while (*s != (char)c)
if (!*s++)
return 0;
return (char *)s;
}
char *strchr(const char *s, int c) {
while (*s && *s != (char)c)
s++;
if (*s == c)
return (char *)s;
return NULL;
}
有人知道为什么吗?为什么不直接将 char
作为参数?
最佳答案
这纯粹是历史原因。请注意,在过去的 C 语言 (K&R C) 中,没有函数原型(prototype) 这样的东西。 strchr
那个时候的函数将被声明为
char *strchr();
并以 K&R 风格定义为
char *strchr(s, c)
char *s;
char c;
{
/* whatever */
}
然而,在 C 语言中(在 K&R C 和现代语言中)如果函数声明时没有原型(prototype)(如上所示),则在每个函数调用中传递的参数都服从所谓的默认值争论促销。在默认参数提升下,任何小于 int
的整数类型(或 unsigned int
)总是转换为 int
(或 unsigned int
)。 IE。当参数未声明时,无论何时传递 char
值作为参数,此值隐式转换为int
, 实际上 body 上通过了 int
. short
也是如此. (顺便说一句,float
在默认情况下会转换为 double
参数提升)。如果在函数内部参数实际上声明为 char
(如上面的 K&R 样式定义),它被隐式转换回 char
键入并用作 char
在函数里面。这就是它在 K&R 时代的工作方式,实际上直到今天,当函数没有原型(prototype)或使用可变参数时,这也是它在现代 C 中的工作方式。
现在,提示现代 C,它具有函数原型(prototype) 并使用现代风格的函数定义语法。为了保留和复制 strchr
的“传统”功能,如上所述,我们别无选择,只能声明strchr
的参数。作为int
并将其显式转换为 char
在函数里面。这正是您在引用的代码中观察到的。这正是 strchr
的功能在标准中有描述。
此外,如果您有一个已编译的遗留库,其中 strchr
如上所示以 K&R 样式定义,您决定为该库提供现代原型(prototype),即 strchr
的正确声明。会是
char *strchr(const char *s, int c);
因为int
是上述遗留实现期望实际接收到的 c
.用 char
声明它参数不正确。
因此,您永远不会看到期望类型为 char
的参数的“传统”标准库函数, short
或 float
.所有这些函数都将使用 int
类型的参数声明或 double
相反。
char 指针和 void *
的标准保证背后有一个非常相同的基本原理。指针共享相同的表示和对齐要求。依靠这个保证你可以申报malloc
作为void *
-返回函数,然后将此声明与标准库的预编译遗留版本一起使用,其中 malloc
实际返回char *
.
引用:C99 基本原理,5.10 版
7.1.4 Use of library functions
/--/
All library prototypes are specified in terms of the “widened” types: an argument formerly declared as char is now written as int. This ensures that most library functions can be called with or without a prototype in scope, thus maintaining backwards compatibility with pre-C89 code
关于c - 为什么 strchr 需要一个 int 来查找 char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8462137/