为什么函数“ memchr()”将“ int”用作“ char”类型的参数? [英] Why does the function `memchr()` use `int` for the argument of `char` type?

查看:65
本文介绍了为什么函数“ memchr()”将“ int”用作“ char”类型的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下函数使用 int 作为第二个参数类型,

The following function uses int as the second argument type,

memchr(const void *buf, int ch, size_t count);

尽管它用于字符类型。为什么将函数定义为对 char 类型的参数使用 int ?有什么特殊原因吗?

Though it is used for a character type. Why is the function defined to use int for the argument of char type? Are there any special reasons for this?

推荐答案

之所以如此,是因为这是一个非常古老的标准函数,它存在于C语言发展的早期。

It is so because this is a very "old" standard function, which existed from the very early times of C language evolution.

旧版本的C没有诸如功能原型之类的东西。函数要么未声明,要么使用未知参数列表声明,例如

Old versions of C did not have such things as function prototypes. Functions were either left undeclared, or declared with "unknown" parameter list, e.g.

void *memchr(); /* non-prototype declaration */

调用此类函数时,所有参数都将自动接受参数提升,这意味着此类函数从未收到过 char short 类型的参数值。此类参数总是由调用者隐式提升为键入 int ,并且函数本身实际上收到了 int 。 (在现代C中,对于如上所述声明的函数,即没有原型,情况仍然如此。)

When calling such functions, all argument were subjected to automatic argument promotions, which means that such functions never received argument values of type char or short. Such arguments were always implicitly promoted by the caller to type int and the function itself actually received an int. (This is still true in modern C for functions declared as shown above, i.e. without prototype.)

最终C语言发展到 prototype 的地步函数声明,将新的声明与标准函数的遗留行为以及已编译的遗留库对齐非常重要。

When eventually C language developed to the point where prototype function declarations were introduced, it was important to align the new declarations with legacy behavior of standard functions and with already compiled legacy libraries.

这就是为什么您永远不会看到 char short 在旧式函数声明的参数列表中。出于同样的原因,您也不会在其中看到任何类型的 float

This is the reason why you will never see such types as char or short in argument lists of legacy function declarations. For the very same reason you won't see type float used there either.

这也意味着,如果由于某种原因必须为K& R样式中定义的某些现有遗留函数提供原型声明,则必须记住在 promoted 参数类型中指定原型。例如。对于定义为

This also means that if for some reason you have to provide a prototype declaration for some existing legacy function defined in K&R style, you have to remember to specify the promoted parameter types in the prototype. E.g. for the function defined as

int some_KandR_function(a, b, c)
char a;
short b;
float c;
{
}

正确的原型原型声明实际上是

the proper prototype prototype declaration is actually

int some_KandR_function(int a, int b, double c);

但不是

int some_KandR_function(char a, short b, float c); // <- Incorrect!

这篇关于为什么函数“ memchr()”将“ int”用作“ char”类型的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆