格式字符串未使用的数据参数 - 输出long

时间:2017-03-02 04:00:44

标签: c timer arguments real-time clock

好的,这是一个C程序......即使我把它正确放置,我也会遇到这个问题。很长的ms和印刷品我有" l"。现在,x是一个全局int变量,用户通过命令行参数输入,x然后是atoi()参数。

此问题发生在一个函数中。我想知道我是否输错了。在尝试输出它之前将int x设置为此long ms变量时,我是否应该进行类型转换?我很困惑,并试图输出毫秒。

    struct timespec now;
 clock_gettime(CLOCK_REALTIME, &now);
 long ms;
 x = ms;
 ms = round(now.tv_nsec / 1.0e6);

 fprintf(stdout, "l: flip\n", ms);

1 个答案:

答案 0 :(得分:0)

我已经用我看到的内容评论了你的代码。

struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
long ms;
x = ms;  
// <== this is assigning a variable 'ms' to the variable 'x'
// however, the variable 'ms' is not initialized 
// this will cause the compiler to raise a warning message
// about using an uninitialized variable
// this is (for the above reason) undefined behavior

ms = round(now.tv_nsec / 1.0e6); 
// <-- initialized the variable 'ms'
// but it is too late for the prior statement
// AND the compiler will not be happy about the 'implied' 
// conversion from the returned type from 'round()' 
// which is 'double' to the type 'long int' of the variable 'ms'
// The compiler will be happy if the line is written like this:
ms = (long int)round( now.tv_nsec / 1.0e6 );


fprintf(stdout, "l: flip\n", ms); 
// <-- will cause the compiler to complain, as you already know

如果代码是:

fprintf(stdout, "%l: flip\n", ms); 
// <-- will also cause the compiler to complain about a invalid format specifier

如果相反,代码将使用与&#39;类型匹配的有效格式说明符&#39;变量&#39; ms&#39; (long int)

fprintf(stdout, "%ld: flip\n", ms); 
// <-- now compiler happy

格式说明符&#39;%ld&#39;表示长整数&#39;

fprintf()(或printf())的手册页会告诉您可用的所有有效格式说明符及其作用。