15 April 2013

Difference between declaration and defination of a function.


first of all there is a big difference between execution and compilation.execution starts at the beginning of the main() and ends in  the main().compilation starts at the beginning of the preprocessed file.
<fieldset><legend></legend>
1.int x();  //compilation will begin at line 1
2.int y();
3.int z();
4.int x=10;
5.int main()
6.{
7.int x=5+10; //execution will start here at line 7
8.return 0; // execution will end here at line 8
9.x=0; // will not executed
10.}
11.int x(){
12.return 5;
13.} //compilation will end here at line 13
</fieldset>
ok what is declaration anyway?
every variable and function must be allocated some memory in order to execute .memory can only be allocated if a function or variable has a defination.
declaration means promising the compiler that the actual defination of the object exists somewhere.you please carry on with the compilation without allocating any memory .as soon as you find the actual defination allocate the memory
lets see in case of a function
<fieldset><legend></legend>
//error no declaration and defination
int main()
{
fun(); // compiler is unware of the fun()
}
</fieldset>
<fieldset><legend></legend>
//compile successfully by compiler but linker will give error as no function defination
// no  defination no memory is allocated yet
int fun();
int main()
{
fun(); // produce error
}
</fieldset>
<fieldset><legend></legend>
// no error will run and compile successfully as fun() was never called
int fun();
int main()
{
//don't call fun() anywhere in the program
}
</fieldset>
<fieldset><legend></legend>
// compiler encounters defination before the function is actually called.it will allocate the space for it.no error
int fun(){
return 0;
}
int main()
{
fun() //will compile successfully
}
</fieldset>
<fieldset><legend></legend>
// error fun() is called .compiler is unaware of the thing named fun()
int main()
{
fun(); //compiler does not know what fun is
}
int fun(){
return 0;
}
</fieldset>
<fieldset><legend></legend>
// no error
int fun(); // declaration.compiler will now know that he it will find the actual defination of fun() somewhere if fun() is called anywhere in the program
int main()
{
fun(); //compiler  know what fun is but space has not been allocated yet
}
int fun(){
return 0;  /* space is now
               allocated */
}
</fieldset>
lets see   in case of variables


SHARE THIS

Author:

0 comments: