Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly cast time_t to long int?

Tags:

c++

casting

I'm still learning about type casting in C++ and I'm currently doing this

long int t = time(NULL);

I'm using VS2013 and noticed the conversion from 'time_t' to 'long' warning so I thought I would type cast it to look like;

long int t = static_cast<long int> time(NULL);

However this doesn't work yet combining a static cast and a C-style cast works

long int t = static_cast<long int> (time(NULL));

I was just wondering if anyone could help shed some light on this?

like image 450
Ryanas Avatar asked Jan 20 '15 12:01

Ryanas


People also ask

Is Time_t a long int?

The variable time_t is a 32-bit long int that can hold values up to 2147483647 before it overflows.

How do you set long int?

We can convert long to int in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Typecasting in java is performed through typecast operator (datatype).

Can you cast long to int in C?

In terms of converting a ( signed ) long long datatype to an unsigned int in C and C++, you can simply cast the data between them: int main()


2 Answers

time(NULL) is not a cast but a function call which returns time_t. Since time_t is not exactly the same type as long int, you see the warning.

Furthermore, static_cast<T>(value) requires the parenthesis, that is why your first version does not work.

like image 53
Sebastian Dressler Avatar answered Oct 23 '22 09:10

Sebastian Dressler


Your question contains the answer. The static_cast generic method in the code you provide takes the time_t type as its input and converts it to a long int as its return value. This code does not contain a C-style type-cast.

long int t = static_cast<long int> (time(NULL));

Type-casting should also work too, because time_t is an arithmetic type and the C cast operator will perform the promotion to the long int type.

long int t = (long int)time(NULL);

This casting tutorial might be an interesting read for you.

like image 22
Evil Dog Pie Avatar answered Oct 23 '22 11:10

Evil Dog Pie