7

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?

Ryanas
  • 1,757
  • 3
  • 19
  • 36

3 Answers3

7

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.

Sebastian
  • 8,046
  • 2
  • 34
  • 58
2

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.

Evil Dog Pie
  • 2,300
  • 2
  • 23
  • 46
0

A time_t value is the number of seconds since the start of Jan 1 1970. Casting that to 32-bit long you therefore restrict yourself to values representing time values before the year 2038, roughly. That's not a good idea, and the ungoodness of it is the reason for your warning.


The attempted expression

static_cast<long int> time(NULL)

is just invalid syntax. A static_cast requires a parenthesis with the value.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Is there no big/little endian matter related to this, which needs to use `ntohl` to be compatible everywhere? – Sandburg Jul 09 '19 at 15:57