mardi 23 décembre 2014

Why is *declaration* of data and functions necessary in C language, when the definition is written at the end of the source code?


Consider the following "C" code:



#include<stdio.h>
main()
{
printf("func:%d",Func_i());
}

Func_i()
{
int i=3;
return i;
}


Func_i() is defined at the end of the source code and no declaration is provide before its use in main(). At the very time when the compiler sees Func_i() in main(), it comes out of the main() and finds out Func_i(). The compiler somehow finds the value returned by Func_i()and gives it to printf(). I also know that the compiler cannot find the return type of Func_i(). It, by default takes(guesses?) the return type of Func_i() to be int. That is if the code had float Func_i() then the compiler would give the error: Conflicting types for Func_i() .


From the above discussion we see that:




  1. The compiler can find the value returned by Func_i().




    • If the compiler can find the value returned by Func_i() by coming out of the main() and searching down the source code, then why can't it find the type of Func_i(), which is explicitly mentioned.





  2. The compiler must know that Func_i() is of type float--that's why it gives the error of conflicting types.






  • If the compiler knows that Func_i is of type float, then why does it still assume Func_i() to be of type int, and gives the error of conflicting types? Why don't it forcefully make Func_i() to be of type float.



I've the same doubt with the variable declaration. Consider the following "C" code:



#include<stdio.h>
main()
{
/* [extern int Data_i;]--omitted the declaration */
printf("func:%d and Var:%d",Func_i(),Data_i);
}

Func_i()
{
int i=3;
return i;
}
int Data_i=4;


The compiler gives the error: 'Data_i' undeclared(first use in this function).




  • When the compiler sees Func_i(), it goes down to the source code to find the value returned by Func_(). Why can't the compiler do the same for the variable Data_i?



Thank you.





Aucun commentaire:

Enregistrer un commentaire