#include <stdio.h>
void main() {
extern int fun(float);
int a=fun(3.5);
printf("%d",a);
}
int fun(aa)
float aa;
{
return ((int)aa);
}
The code block mentioned above compiles fine on my Visual Studio 8 compiler though output is a junk value. But when I compiled the same code on gcc-4.3.4, I got the following compilation error:
prog.c:2: warning: return type of ‘main’ is not ‘int’
prog.c:8: error: conflicting types for ‘fun’
prog.c:3: error: previous declaration of ‘fun’ was here
How will it work when it has following properties:
- There is a variable declaration before the beginning of function body.
- The function definition does not have the parameter type of the variable.
The function is written in K&R style, and your prototype for it is incorrect. In fact, there are other problems too…
The return type of
main()isint, at least in Standard C. Your print statement should include a newline.Your prototype would be OK if the function
fun()were written with a prototype:However, the function is written in K&R style, and therefore the function expects to be passed a
doublewhich it will convert tofloat:In K&R C, all
floatvalues were passed asdouble. This is why you are getting garbage; you are lying (probably unwittingly) to your compiler, and it is getting its own back by doing GIGO on you.FWIW: GCC 4.6.1 refuses to compile your code (even without any warning settings). It complains:
You can fix this in a number of different ways:
Or:
Or:
Or:
Or:
I believe these are all correct and they all should compile without warnings (unless you ask the compiler to complain about old style (K&R) function definitions, etc).
With GCC set to rather fussy, I get the warnings: