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:
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 themain()
and searching down the source code, then why can't it find the type of Func_i(), which is explicitly mentioned.
- If the compiler can find the value returned by
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 assumeFunc_i()
to be of type int, and gives the error of conflicting types? Why don't it forcefully makeFunc_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?
Edit:
I don't know the details of the inner working of compiler, assembler, processor etc. The basic idea of my question is that if I tell(write) the return-value of the function in the source code at last, after the use of that function then the "C" language allows the computer to find that value without giving any error. Now why can't the computer find the type similarly. Why can't the type of Data_i be found as Func_i()'s return value was found. Even if I use the extern data-type identifier;
statement, I am not telling the value to be returned by that identifier(function/variable). If the computer can find that value then why can't it find the type. Why do we need the forward declaration at all?
Thank you.
Func_i
invalid. There never was a rule to implicitly declare undefined variables, so the second fragment was always malformed. (Yes, compilers do accept the first sample still because it was valid, if sloppy, under C89/C90.)