简体   繁体   English

编译时的 sprintf 格式警告

[英]sprintf format warnings when compiling

Variable freq is declared as follows:变量freq声明如下:

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). freq的格式说明符"%1.1f"显然是float的(我认为)。
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 ?为什么"%1.1f"期望double Shouldn't "f" stand for float? "f"不应该代表浮动吗?
How can I get rid of that warning?我怎样才能摆脱那个警告?

Why %1.1f expects double?为什么 %1.1f 期望双倍? Shouldn't "f" stand for float? “f”不应该代表浮动吗? How can I get rid of that warning?我怎样才能摆脱那个警告?

"%1.1f" expects a double as specified by the C standard. "%1.1f"需要 C 标准指定的double精度值。
In C, double is the default floating-point type for FP ... arguments and constants.在 C 中, double是 FP ... arguments 和常量的默认浮点类型。

... arguments of type float are converted to double before being passed. ...浮点类型的 arguments 在被传递之前被转换为double float 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 .想想"%f"暗示浮点的定点格式,而不是float

Compiler is buggy or simply designed that way and therefore non-compliant to C.编译器有问题或只是以这种方式设计,因此不符合 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 .注意:如果不兼容的编译器在...参数时故意不将float提升为double ,则sprintf()可能支持作为扩展的某些标志,例如"%$f"以指示参数是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);即使在工作机器上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 .很可怕,因为缓冲区可能会FLT_MAX类的大freq而溢出。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM