Prototyping in C

88 Views Asked by At

I'm learning C in a tutorial. They talk about prototyping but for me, the following code works :

double aireRectangle(double largeur, double hauteur) {
    return largeur * hauteur;
}

int main() {
    return aireRectangle(10, 30);
}

They tell that we have to add a ";" after aireRectangle for that works but it works for me... I do not understand why it works for me.

Do you know the reason?

2

There are 2 best solutions below

0
Vipin Nagar On

Let's understand how compilation works in this case. While compilation, the compiler starts from the beginning (or top) of the file and starts compiling your code. Now, in this code before reaching the main program compiler already knows that you have a function aireRectangle defined in the same file. Now, try to define function aireRectangle below the main function. In this case you will get an error saying undefined reference to aireRectangle. In this case compiler does not know what is function aireRectangle when it is inside main function's body. But if you define a function prototype before main function then when compilation will reach to main function it will know that there is some function named aireRectangle is defined somewhere in this file. So it will not generate any error. In such scenarios you will need a function prototype.

There are many more case like if you want to call your function inside many c files, in that case the best approach is to define a function prototype in some header file and its definition in some c file and then include that header file wherever you want to use (or call) that function.

0
Syed Waris On

It is working for you because you are defining the function aireRectangle first and then using it. In your case, the compiler already 'knows' about the function before it is called.

If you define a function after you are using then you need its prototype on top:

int main() {
    return aireRectangle(10, 30);    // You are using function before defining
}

double aireRectangle(double largeur, double hauteur) {     // definition is later
    return largeur * hauteur;
}

In above, the definition of function is after its usage. So in above cases you need to have a prototype on top. This is because the compiler may 'know' that there will be a function defined later.

You will need to to have prototype on top: double aireRectangle(double largeur, double hauteur);

This rule is not strict and some compilers are lenient towards this rule.