Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

c - K&R style function definition problem

The following code works:

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

but this one does not:

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

Why does this happen?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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

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.

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.

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...