Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C need prototype functions while Java does not? [duplicate]

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?

like image 450
ericgrosse Avatar asked Oct 16 '25 13:10

ericgrosse


1 Answers

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.

like image 59
Ziffusion Avatar answered Oct 19 '25 03:10

Ziffusion