为什么C需要原型函数,而Java不需要呢? [英] Why does C need prototype functions while Java does not?

查看:376
本文介绍了为什么C需要原型函数,而Java不需要呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我参加了一门Java课程,并试图用K& R教自己C。目前为止这么好,但我不明白原型的目的。请参阅以下代码中的// 2注释:

  #include  

float convert(int); ** //为什么需要...... **

main()
{
int i; (i = 0; i <= 300; i + = 20)
printf(F:%3d C:%6.1f \ n),一世));

系统(暂停);
返回0;


float convert(int f)** //当我们已经有了这个**
{
float c =(5.0 / 9.0)*( F-32.0);
return c;



$ b $ p
$ b

在Java中,你需要声明一个类似于 public static float convert(int f)并且根本不需要原型。这对我来说似乎更简单。为什么不同?

解决方案

这实质上是为语言系统做出的决定。 $ b

请注意,Java和C编译器都需要知道函数签名,以便它们可以进行类型检查并编译代码。 另外请注意,像C这样的语言需要你分别提供这个签名/原型(在声明中),而实际上函数定义具有完全相同的信息。所以,这基本上是信息的重复。为什么是这样?实质上,这是为了在没有包含定义的实际源代码的情况下编译代码。因此,如果库是以二进制代码的形式提供的,那么使用包含原型的头文件足以允许编译使用库中代码的其他代码。



更多的现代语言,如Java和C#不再需要重复这个原型信息。他们如何编写代码,当他们确实需要原型时?他们在处理定义时将原型信息与二进制代码一起存储。所以,实际上,原型信息只是由编译器自动生成的。


I've taken a Java course and am trying to teach myself C with K&R. So far so good but I don't understand the purpose of prototypes. See the 2 // comments in the code below:

#include <stdio.h>

float convert(int); **//Why is this needed...**

main()
{
    int i;

    for(i = 0; i <= 300; i += 20)
        printf("F: %3d C: %6.1f\n",i,convert(i));

    system("Pause");
    return 0;
}

float convert(int f) **//When we already have this?**
{
    float c = (5.0/9.0) * (f-32.0);
    return c;
}

In Java, you'd declare a function something like public static float convert(int f) and not need a prototype at all. That seems much simpler to me. Why the difference?

解决方案

This is essentially a decision made for a language system.

Note that both the Java and C compilers need to know the function signature so that they can do type checking, and compile the code.

Also note that languages like C need you to supply this signature / prototype separately (in a declaration), when in fact the function definition has the exact same information. So, it is basically a repetition of the information. Why is this? Essentially, this is so that code can be compiled in the absence of the actual source code that contains the definition. So, if a library is supplied as binary code, then having the headers which contain the prototypes is enough to allow the compilation of other code that uses the code from the library.

More modern languages like Java and C# do away with the need to repeat this prototype information. How do they then compile code, when they do need the prototype? What they do is store the prototype information along with the binary code, at the time they process the definition. So, really, the prototype information is just auto generated by the compiler itself.

这篇关于为什么C需要原型函数,而Java不需要呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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