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