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?
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?
I think you are using Visual C++. The return type of time(0)
is 64bit int
even if you are programming for 32bit
platform unlike g++
. To remove the warning, just assign time(0)
to 64bit
variable.
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.
#include<time.h>
//...
time_t n = time(0);
//...
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 returns time_t
and not integer. Use that type preferably because it may be larger than int
.
If you really need int
, then typecast it explicitly, for example:
int n = (int)time(0);
You probably want to use a type of time_t instead of an int.
See the example at http://en.wikipedia.org/wiki/Time%5Ft.