olpa olpa - 26 days ago 8
C Question

Arguments type conversion if a function is K&R-style defined

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.));
}

Answer

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.