如何消除 C++ 中 time.h 的警告?
当我使用它时,
#include<time.h>
//...
int n = time(0);
//...
我收到有关将时间转换为 int 的警告。有没有办法消除这个警告?
When I use this
#include<time.h>
//...
int n = time(0);
//...
I get a warning about converting time to int. Is there a way to remove this warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,将 n 更改为
time_t
。如果您查看大多数/所有系统上 time.h 中的签名,您会发现这就是它返回的内容。请注意,Arak 是正确的:使用 32 位 int 是一个问题,至少 由于 2038 错误。但是,您应该考虑到,对整数 n(而不是 time_t)进行的任何类型的算术只会增加您的代码提前遇到该错误的可能性。
PS:如果我在原始答案中没有说清楚,对编译器警告的最佳响应几乎总是解决您被警告的情况。例如,将较高精度的数据强制转换为较低精度的变量会丢失信息 - 编译器试图警告您,您可能刚刚创建了一个地雷错误,直到很久以后才会有人绊倒。
Yes, change n to be a
time_t
. If you look at the signature in time.h on most / all systems, you'll see that that's what it returns.Note that Arak is right: using a 32 bit int is a problem, at a minimum, due to the 2038 bug. However, you should consider that any sort of arithmetic on an integer n (rather than a time_t) only increases the probability that your code will trip over that bug early.
PS: In case I didn't make it clear in the original answer, the best response to a compiler warning is almost always to address the situation that you're being warned about. For example, forcing higher precision data into a lower precision variable loses information - the compiler is trying to warn you that you might have just created a landmine bug that someone won't trip over until much later.
时间返回
time_t
而不是整数。最好使用该类型,因为它可能大于int
。如果您确实需要
int
,则显式地对其进行类型转换,例如:Time returns
time_t
and not integer. Use that type preferably because it may be larger thanint
.If you really need
int
, then typecast it explicitly, for example:我认为您正在使用 Visual C++。即使您是针对与
g++
不同的32bit
平台进行编程,time(0)
的返回类型也是64bit int
。要删除警告,只需将time(0)
分配给64bit
变量即可。I think you are using Visual C++. The return type of
time(0)
is64bit int
even if you are programming for32bit
platform unlikeg++
. To remove the warning, just assigntime(0)
to64bit
variable.您可能想使用 time_t 类型而不是 int 类型。
请参阅 http://en.wikipedia.org/wiki/Time_t 中的示例。
You probably want to use a type of time_t instead of an int.
See the example at http://en.wikipedia.org/wiki/Time_t.
原因是 time() 函数返回 time_t 时间,因此在这种情况下您可能需要静态转换为 int 或 uint。这样写:
The reason is time() functions returns a time_t time so you might need to do a static cast to an int or uint in this case. Write in this way: