views:

171

answers:

4

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?

+1  A: 

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.

AraK
+19  A: 

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.

Bob Cross
I think this is the correct answer :)
AraK
@AraK, saw your comment above and you made a good point about 2038.
Bob Cross
+2  A: 

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);
Viliam
If your program is gonna work until 2038 you got a problem ;)
AraK
Though technically the correct answer to the question. This is not a good idea. Better to convert your code to use time_t
Martin York
This treats the symptoms and not the illness.
Michael Aaron Safyan
Hey, just read the answer. I said "use that type preferably".
Viliam
As well as the size issue, `time_t` is permitted by POSIX to be a floating-point type, not any size of integer.
Steve Jessop
@onebyone, which only makes it worse, of course.
Bob Cross
+1  A: 

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.

Mark