0

This is the (pretty common, I'll add) code that you find for displaying the current in time in C and C++.

time_t tt; 
struct tm * ti; 
time (&tt); 
ti = localtime(&tt);
cout << asctime(ti);

This is what I do understand:

  1. time_t is the data type that stores time values. tt is an object of that.
  2. struct tm is a structure in the ctime header file.

  3. I can't seem to wrap my head around what ti is. It seems to be a pointer object of tm, but why is the "struct" keyword being used here? Isn't tm an already existing structure?

  4. What is time(&tt)? Storing the value of time in tt?

Lundin
  • 195,001
  • 40
  • 254
  • 396
Aryaman
  • 109
  • 1
  • 1
    3: You use the bonus `struct` keyword because you had to in C. – doctorlove Aug 22 '18 at 08:13
  • 1
    pretty common in C++? not really.... – 463035818_is_not_an_ai Aug 22 '18 at 08:13
  • [chrono](http://www.cplusplus.com/reference/chrono/) would be the way to go today in C++. – Hannes Hauptmann Aug 22 '18 at 08:15
  • In both C and C++, the ampersand (`&`) applied to an *expression* is the "address-of" operator and produces a pointer. In C++, `&` in a *type* indicates a reference type. There are no references here. – molbdnilo Aug 22 '18 at 08:27
  • BTW - there are no references here - as your question mentions. The `&tt` is getting the address of `tt` in each case. This is C, not C++. – doctorlove Aug 22 '18 at 08:27
  • @user463035818 my bad! Sadly, the compiler and books I'm using are very old (I'm using DOSBOX, Turbo C++) thanks to the syllabus of my school, which is why I turned a blind eye to it. :P – Aryaman Aug 22 '18 at 08:34
  • Much of my confusion was because this code is C code being used in C++. My apologies! – Aryaman Aug 22 '18 at 08:34

2 Answers2

0
  1. You're (partially) right. tt is not an object, it's a variable of type time_t
  2. Yup
  3. struct tm * is a datatype: a pointer to a struct tm. If you are not familiar with this, try to implement in pure C a stack or a queue or a chained list.

  4. RTFM: from the doc (man 2 time)

time_t time(time_t *tloc);

DESCRIPTION
time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).

If tloc is non-NULL, the return value is also stored in the memory pointed to by tloc.

So yes, the time is now stored in ti and in tt. See What is the difference between clock_t, time_t and struct tm?

politinsa
  • 3,480
  • 1
  • 11
  • 36
0
time_t tt;  // a data type to store the number of seconds since the epoch
struct tm * ti;  // a structure that stores the number of seconds decoded into
                 // integers for year, month, day, hour, etc
time (&tt);      // get the current time and store it in tt
ti = localtime(&tt);  //decode the seconds into separate year/month/day/etc ints
cout << asctime(ti);  // convert the ints into string representation and print it
Spoonless
  • 561
  • 5
  • 14