Is there a printf specifier that requires the float not double?

I get errors like MISRA when I use the "% f" specifier for snprintf with a parameter of type float .

According to my research, MISRA is correct because "% f" expects a double .

Is there a specifier or modifier with a floating point that will use a parameter of type float , not double ?

I am working on an embedded system and do not want to convert from a 32-bit float to a 64-bit double in order to satisfy the snprintf function. The code prints to the debug / console port, and this is the only place where the conversion takes place.

For those of you who have sample code:

 // This section is for those C++ purists and it fulfills the C++ tag. #if __cplusplus #include <cstdio> #else #include <stdio.h> #endif #define BUFFER_SIZE (128U) int main(void) { char buffer[BUFFER_SIZE]; float my_float = 1.234F; // The compiler will promote the single precision "my_float" // to double precision before passing to snprintf. (void)snprintf(buffer, BUFFER_SIZE, "%10.4f", my_float); puts(buffer); return 0; } 

All my research on SO and Web is about printing floating point values, and not about which qualifiers, the float parameter will be needed so as not to advance to double .

I am using the IAR Embedded Workbench compiler for the ARM7TDMI processor.

+6
source share
4 answers

No, because printf and his friends are variable functions, so the float parameter is automatically converted to double as part of the default arguments (see section 6.5.2.2 of the C99 standard).

I am not sure why this causes a MISRA warning, although I cannot figure out how this could be dangerous.

+20
source

No, no, because standard advertisements convert each float argument to double when passed through a list of variable parameters.

+9
source

A proper analysis of compliance with MISRA-C: 2004 should give:

  • Violation 1.1, the code does not comply with ISO 9899: 1990 (C ++ code, C99 code).
  • Violation 2.2, use of // comment.
  • Violation 16.1, the use of variable function arguments.
  • Violation 20.9, use of stdio.h.

If you get errors other than the ones above, your static analyzer may be broken.

I analyzed manually as well as with the LDRA 7.6.0 test line.

+5
source

It is not possible to specify a float instead of a double in the printf functions due to automatic dispatch, but I think you can change your code:

 (void)snprintf(buffer, BUFFER_SIZE, "%10.4f", my_float); 

in

 (void)snprintf(buffer, BUFFER_SIZE, "%10.4f", (double)my_float); 

and achieve the right result

0
source

All Articles