Chinaunix首页 | 论坛 | 博客
  • 博客访问: 134762
  • 博文数量: 47
  • 博客积分: 2405
  • 博客等级: 大尉
  • 技术积分: 385
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-28 09:33
文章分类

全部博文(47)

文章存档

2014年(5)

2012年(5)

2011年(7)

2009年(30)

我的朋友

分类: C/C++

2009-06-17 22:47:50

《The C Programming Language Second Edition》中下面这个函数调用:
  qsort((void **) lineptr, 0, nlines-1, (int (*)(void *, void *))(numeric ? numcmp : strcmp));
  其中,使用了两次强制类型转换,其中第二甚至是利用指向函数的指针,将函数的类型进行了转换。当然上面语句在某些编译器上无法通过,因为某些编译器要求条件表达:
  表达式1 ? 表达式2 : 表达式3
  中表达式2与表达式3的类型相同。当然这样的要求是不符合ANSI标准的。在ANSI标准中,假如表达式2与表达式3的类型不同,则结果的类型由类型转换规则决定。当然,我们可以变同一下,先将两个函数的类型进行强制转换来达到目的:
  qsort((void **) lineptr, 0, nlines-1, numeric ? (int (*)(void *, void *))numcmp : (int (*)(void *, void *))strcmp));
或者使numcmp函数与strcmp函数的类型完全一致,声明numcmp为
int numcmp(const char *, const char *);




The reason a mismatch can happen is that if there is no function prototype, a
function is implicitly declared by its first appearance in an expression, such as
    sum += atof(line)
If a name that has not been previously declared occurs in an expression and is followed by a
left parentheses, it is declared by context to be a function name, the function is assumed to
return an int, and nothing is assumed about its arguments. Furthermore, if a function
declaration does not include arguments, as in
    double atof();
that too is taken to mean that nothing is to be assumed about the arguments of atof; all
parameter checking is turned off. This special meaning of the empty argument list is intended
to permit older C programs to compile with new compilers. But it's a bad idea to use it with
new C programs. If the function takes arguments, declare them; if it takes no arguments, use
void.
一定不要忘记声明函数原型。如果忘记了声明函数原型,就会引起隐式声明,编译时不会报错,但是连接后运行程序会出现某些错误,这是由于隐式声明与函数定义类型不匹配造成的.
int fun(void);

阅读(1046) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~