Reputation: 430
Variable freq
is declared as follows:
void exciteFreqN(float freq, unsigned short N)
then I use the following instruction:
sprintf(debugstr, "Cntr ticks:%d freq:%1.1f\r\n", ctphp, freq);
Format specifier "%1.1f"
for freq
is clearly float
(I think).
However, the compiler warns:
acquisitionXBEE.c: In function 'exciteFreqN':
***acquisitionXBEE.c:8519:5: warning: format '%1.1f' expects type 'double', but argument 4 has type 'float'
Why "%1.1f"
expects double
? Shouldn't "f"
stand for float?
How can I get rid of that warning?
Upvotes: 0
Views: 382
Reputation: 153517
Why %1.1f expects double? Shouldn't "f" stand for float? How can I get rid of that warning?
"%1.1f"
expects a double
as specified by the C standard.
In C, double
is the default floating-point type for FP ...
arguments and constants.
...
arguments of type float
are converted to double
before being passed. sprintf(debugstr, "%1.1f %1.1f %1.1f ", 1.0, 2.0f, freq);
should work.
Think of "%f"
implying fixed-point format for floating-point, not float
.
Compiler is buggy or simply designed that way and therefore non-compliant to C.
A cast may quiet the warning:
sprintf(debugstr, "Cntr ticks:%d freq:%1.1f\r\n", ctphp, (double) freq);
Report bug and/or move to another compiler.
Note: If the non-compliant compiler purposely does not promote float
to double
when a ...
argument, sprintf()
may support, as an extension, some flag, like "%$f"
to indicate the argument is a float
. Check your compiler documents. Be wary then of making such implementation specific code.
Warning
Even on a working machine sprintf(debugstr, "Cntr ticks:%d freq:%1.1f\r\n", ctphp, freq);
is scary as the buffer may overrun with a large freq
like FLT_MAX
.
Control width, size and be more informative. What good is a debug message that causes a buffer overflow or is not so informative?
// snprintf, v----size-----v %g
snprintf(debugstr, sizeof debugstr, "Cntr ticks:%d freq:%g\r\n", ctphp, freq);
// ... or pedantically to see all useful precision
snprintf(debugstr, sizeof debugstr, "Cntr ticks:%d freq:%.*g\r\n",
ctphp, FLT_DECIMAL_DIG, freq);
Upvotes: 1