Home > OS >  Access specfiers in C
Access specfiers in C

Time:12-22

#include <stdio.h>

int main()
{
  float i;
  i=1;
  printf("%d",i);
  return 0;
}

What should be the output of the code? Online compilers are giving garbage value but according to my logic shouldn't the float be converted to int and the float part get truncated and just print 1 as the output?

CodePudding user response:

It's made quite clear in the standard (e.g., C17 7.21.6.1 The fprintf function /9) that it is undefined behaviour of your argument types don't match the format specifiers:

9/ If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

So, in response to your question "What should be the output of the code?", the answer is "Whatever the implementation decides is best."

CodePudding user response:

No conversion is taking place in the way you assumed (*). The format specifier in the format string is used to determine what data type is expected next by va_arg. If the type specified in the format string does not match the type actually passed as parameter, behavior is undefined.


(*): With variadic arguments like printf there is a different type of conversion called "default argument promotion" happening, but that is a different subject altogether and is not being the issue you're facing.

  • Related