Reputation: 11
Writing the body of the function before the main function without declaring runs correctly.But writing the function's body after the main function needs a declaration of the function explicitly.Why?
Upvotes: 0
Views: 101
Reputation: 55
Since, C is a Top down approach. This works on "functional decomposition" concept. So, it takes definition as declaration in 1st case as follows:
void display()
{
printf("hai");
}
void main()
{
display();
}
But, in second case, while parsing compiler searches for declaration.
Upvotes: 0
Reputation: 222660
A definition is a declaration.
When you define the function before it is called, you are also declaring it.
At the point where a function is called, a declaration for it should have appeared previously. A definition satisfies this requirement. If the definition appears after it is called, there must be a separate declaration before the call.
Upvotes: 4
Reputation: 2576
Because of the way files are processed by the compiler from top to bottom.
A function becomes known to the compiler when it encounters it, therefore functions whose body is written (aka, defined) above their use in the file are known of the compiler and do not trigger an error, while those defined after their use trigger such an error.
Relying upon the function declaration order is bad practice, however. You should use a header file.
Upvotes: 2
Reputation: 21258
At the point of reaching the call site, in a textual scan starting from the first, finishing at the last, byte of the compilation unit, the type of any function called must be known. This means that any function defined (this also declares the function) before its call site is fine.
Upvotes: 5