I’m getting MISRA type errors when I use “%f” specifier for snprintf with a parameter of type float.
According to my research, MISRA is correct because “%f” expectes a type of double.
Is there a floating point specifier or modifier that will use a float type parameter and not a double?
I’m working on an embedded system and don’t want to convert from 32-bit float to 64-bit double just to please 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 needing a code example:
// 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 the Web is about printing a floating point value, not about which specifiers will require a float parameter so that no promotion to double takes place.
I am using IAR Embedded Workbench compiler for ARM7TDMI processor.
No, because
printfand its friends are variadic functions, so afloatparameter undergoes automatic conversion todoubleas part of the default argument promotions (see section 6.5.2.2 of the C99 standard).I’m not sure why this triggers a MISRA warning though, I can’t think of any way in which this might be dangerous.