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?
The variable time_t is a 32-bit long int that can hold values up to 2147483647 before it overflows.
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).
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()
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With