Chinaunix首页 | 论坛 | 博客
  • 博客访问: 395003
  • 博文数量: 138
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1620
  • 用 户 组: 普通用户
  • 注册时间: 2013-03-10 16:55
个人简介

当你比别人优秀一点点,别人会嫉妒你。当你比别人优秀很多,别人会羡慕你。

文章分类

全部博文(138)

文章存档

2016年(2)

2015年(2)

2014年(15)

2013年(119)

我的朋友

分类: LINUX

2013-03-10 16:57:29

为什么很多C库的函数参数列表,应该用char却用了int,比如memset ()strchr()等等

The reasons for that are purely historical. Note, that in the old days of C language (K&R C) there was no such thing as function prototype. A strchr function in those times would be declared as

char *strchr();

and defined in K&R style as

char *strchr(s, c) char *s; char c; { /* whatever */ }

However, in C language (in K&R C and in the modern one as well) if the function is declared without a prototype (as shown above), the parameters passed in each function call are subjected to so called usual arithmetic conversions. In usual arithmetic conversions any integral type smaller than int (or unsigned int) is always converted to int (or unsigned int). I.e. when the parameters are undeclared, whenever you pass a charvalue as an argument, this value is implicitly converted to int, and actually physically passed as an int. The same is true for short. (BTW, float is converted to double by the same process). If inside the function the parameter is actually declared as a char (as in the K&R style definition above), it is implicitly converted back to char type and used as a char inside the function. This is how it worked in K&R times, and this actually is how it works to this day in modern C when function has no prototype or when variadic parameters are used.

How, cue in the modern C, which has function prototypes and uses modern-style function definition syntax. In order to preserve and reproduce the "traditional" functionality of strchr, as described above, we have no other choice but to declare the parameter of strchr as an int and explicitly convert it to char inside the function. This is exactly what you observe in the code you quoted. This is exactly as the functionality of strchr is described in the standard.

Moreover, if you have an already-compiled legacy library, where strchr is defined in K&R style as shown above, and you decided to provide modern prototypes for that library, the proper declaration for strchr would be

char *strchr(const char *s, int c);

because int is what the above legacy implementation expects to physically receive as c. Declaring it with achar parameter would be incorrect.

For this reason, you will never see "traditional" standard library functions expecting parameters of type char,short or float. All these functions will be declared with parameters of type int or double instead.


本文链接来自

上也写的比较详细!




阅读(555) | 评论(0) | 转发(0) |
0

上一篇:gcc 和 binutils 关系

下一篇:linux alias

给主人留下些什么吧!~~