+ 2
What is the need to first declare a function and then define it .??
4 ответов
+ 2
Well take a look at code below.
void main()
{
/*line number 3*/ func() ;
}
void func()
{
do something
}
Compiler starts compiling from the top(or main) of the code.
When compiler comes to line number 3 it looks for func() function but it haven't seen anything named that so far. So it gives an error.
As you already know you can solve adding this
void func() ;
before main function. In that case when it comes to line number 3 it have seen something named func. So it doesn't give an error.
line void func() is actually a promise to the compiler that there is a function named func() defined(func's body) is somewhere in the code.
After successfully compiled linker searches for func() body and links it to func() in line number 3.
You can also do this
void func()
{
do something
}
void main()
{
/*line number 3*/ func() ;
}
+ 1
Because if you have defined the function below main() and not declared the prototype above the main() then while the program is executing then it starts from main() and it will completely ignore the function because it wouldn't know that it exists.
So a declaration of a function on the top tells the compiler that a function exists in the program which has to be executed.
Also remember the execution is done in a top to bottom manner.
0
Just like Avinesh said, that the C++ is procedural and source file executed from top to bottom. Functions used in eg. main() must be declared before use. Build system then searches for definitions of declared functions somewhere. Just you can also define the whole function just before main and use it in main — you then declare that it exists AND define at the same time. Noone will recommend you to do so though because it's a bad practice and clutters the source file making it difficult to read, as everyone reading would assume you list all the custom functions (meaning declarations) before main and after presenting the logic of a source file you define all the functions declared before.
It's also true while you write header files. In headers we put the declarations, linker then finds and links the sources to include definitions of the needed functions.