K&安培; R风格的函数定义问题 [英] K&R style function definition problem

查看:287
本文介绍了K&安培; R风格的函数定义问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code工作:

int main()
{
   void foo(int);
   foo(3);
   return 0;
}
void foo(a) int a;
{
   printf("In foo\n");
}

但是这一次不会:

but this one does not:

int main()
{
   void foo(float);
   foo(3.24);
   return 0;
}
void foo(a) float a;
{
   printf("In foo\n");
}

为什么会出现这种情况?

Why does this happen?

推荐答案

这与C语言的演变,以及安排是向后兼容较旧口味的方式做。

Actually, kind of an interesting question.

This has to do with the evolution of the C language and the way it arranges to be backwards-compatible to the older flavors.

在这两种情况下,你有一个K&安培;对于 R-时代定义富(),但C99的声明(有原型)早些时候

In both cases, you have a K&R-era definition for foo(), but a C99 declaration (with prototype) earlier.

但在第一种情况下, INT 的默认参数实际上是参数,所以函数调用是兼容的。

But in the first case, the default parameter of int actually is the parameter, so the function call is compatible.

在第二种情况下,虽然,K&放大器; R的定义标准参数提升带来了从K&放治; R时代和参数的类型真的是双击

In the second case, though, the K&R definition brings in the standard argument promotions rule from the K&R era and the type of the parameter is really double.

但是,你在调用点使用现代化的雏形,使其成为浮动。因此,在调用现场code可能会推一个真正的浮动,这是在任何情况下,从双击

But, you used a modern prototype at the call site, making it a float. So the code at the call site might have pushed a real float, which is in any case a distinct type from double.

如果所有引用的foo()是K&安培; R风格,我相信最,你会得到将是一个警告,这是编译器会做当时,编译器必须采取行动,像编译传统code。它甚至会是一个类型安全的通话,因为花车都会被提升一倍,至少在程序调用接口。 (不一定为内部函数code)

If all of the references to foo() were K&R style, I believe the most you would get would be a warning, which is what compilers would have done back then, and the compiler must act like that to compile the legacy code. It would even have been a type-safe call because the floats would all be promoted to double, at least for the procedure call interface. (Not necessarily for the internal function code.)

这篇关于K&安培; R风格的函数定义问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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