Even if a function is defined in the K&R style, I expect that the type conversion for the arguments should happen. However, the output from the test program is:
int 9.42
int 2.97005e-12
flt 9.42
flt 9.42
It seems that the int value isn't converted to double. Why?
#include <stdio.h>
double mult_pi_usual(double v) {
return v * 3.14;
}
double mult_pi_KR(v)
double v;
{
return v * 3.14;
}
int main() {
printf("int %g\n", mult_pi_usual(3));
printf("int %g\n", mult_pi_KR(3));
printf("flt %g\n", mult_pi_usual(3.));
printf("flt %g\n", mult_pi_KR(3.));
}
As a declaration, the K&R style does not convey type information for checking at the call point.
Consider the fact that a K&R function declaration (e.g. in a header) would be
double mult_pi_KR();
and the double v is only visible within the function definition.
For consistency across compilation units (not all will have visibility of the complete function definition), the type of the argument is not checked when calling the function.
In your example, this means the compiler - at points where the function in CALLED - does not know that mult_pi_KR() accepts a double. So mult_pi_KR(3) does not promote 3 to double.
The result of passing an int to a function expecting a double is actually undefined behaviour.
From the C89/C90 standard (6.3.2.2):
If the function is defined with a type that does not include a prototype, and the types of the arguments after promotion are not compatible with those of the parameters after promotion, the behavior is undefined.
When you are passing the value 3 to a double parameter in mult_pi_KR(3), an undefined behaviour is invoked and somehow, the value getting stored inside v comes to be 0.000000. Nothing can be said about this value this is an undefined behaviour. Since 0 is never precisely stored in floating-point representation, multiplying it with 3.14 gives strange a value like 2.97005e-12.
I have tried the same example but changed the type of v to int in mult_pi_KR. Then, the first call to mult_pi_KR works just fine, but due to the type mismatch in the second call to it, the value 1 is getting stored in v. Again, a value due to undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With