Implicit function conversion is for double argument to int parameter

Viewed 72
#include <stdio.h>
int main() { 
 foo(22.3);

return 0;
}

void foo(int x) {
 printf("%d", x);
}

Prints 1. Why isn't it printing 22 instead? I believe that when I call foo without declaring an explicit prototype, c generates an implicit prototype that converts short and char to int, and float to double in the function arguments. So 22.3 isn't touched in the call to foo(22.3) and then in the callee function, the parameter int x gets assigned to 22.3: int x = 22.3 which results in numeric conversion wherein the fractional part gets dropped, leaving just 22 in x. So why isn't it printing 22 instead of 1 ?

I think I've got it wrong as to what happens when a caller calls a callee, with mismatched parameter types?

2 Answers

You're calling a function with parameters that are not compatible with the arguments. Because the function doesn't have a prototype, the double-to-int conversion doesn't occur. This results in undefined behavior.

If you were to pass an int, or a smaller integer type that would be promoted to int, then the function would work.

You forgot about function prototype:

#include <stdio.h>

void foo(int); // <--- here!

int main() { 
 foo(22.3);

 return 0;
}

void foo(int x) {
 printf("%d", x);
}

Without this, the compiler probably takes bytes from the beginning of your float value 22.3 and treats them as integer value.

Related