3
#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?

User626468
  • 57
  • 5
  • 1
    Does this answer your question? [Passing float to a function with int argument (that is not declared beforehand)](https://stackoverflow.com/questions/42549605/passing-float-to-a-function-with-int-argument-that-is-not-declared-beforehand) – OldProgrammer Dec 11 '20 at 23:42
  • Do yourself a favor: Turn on warnings in your compiler (whatever broad category it has, like “all” or “most”, so `-Wmost` or `-Wall` on the command line for Clang or GCC), set it to treat warnings as errors (`-Werror`), and set it to use the latest version of the C standard it supports (for GCC or Clang, use `-std=c17`, `-std=c11`, or `-std=c99`). This will disable use of functions without prototypes and give you errors for mismatched arguments. You may get more errors initially, but you will suffer less grief in the long run. – Eric Postpischil Dec 11 '20 at 23:46

2 Answers2

2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    So what I'm getting out of this is that when you call a function with arguments that can't be implicitly converted to match the function's parameters and that don't get further converted by the implicit prototype generated ( double won't get promoted to double because it's already double ), it leads to undefined behavior? Had I called `foo('a')`, by the rules of implicit prototype conversions, the argument 'a' would've been promoted to an int which is compatible with the function's parameters, and so everything would have worked in the end, I may assume. – User626468 Dec 11 '20 at 23:50
1

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.

VillageTech
  • 1,968
  • 8
  • 18