structs in main method?

hi guys I came across this small block of code which I don't understand

I'm guessing tm is a struct included with <ctime> BUT why do you have to put struct infront of it,surely this struct is already made,we are not declaring it so why do you need to put struct before tm

thanks

1
2
3
4
5
6
7
8
9
10
11
12
  #include <ctime>
#include <iostream>
using namespace std;

int main() {
    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << endl;
}
why do you need to put struct before tm

You don't (this is only necessary in C).
You don't - only C enforces it. If a struct is declared this way:
1
2
3
typedef struct time {
//some declerations
} struct time

in C you have to write struct tm. Don't worry about it, C++ doesn't enforce it.
Last edited on
thanks for the reply guys

so if I was to use the tm class in c++ I wouldn't have to put a struct before it?

thanks
You won't have to - I generally do it because it's more "correct". If the code's within an extern "c" block, then you have to add the struct because of C linkage.
ndrewxie wrote:
I generally do it because it's more "correct"

Bjarne Stroustrup, The C++ Programming Language Fourth Edition, 8.2.2 - struct Names:
For reasons that reach into the prehistory of C, it is possible to declare a struct and a non-struct with the same name in the same scope. For example:
1
2
3
4
struct stat { /*
...
*/ };
int stat(char∗ name, struct stat∗ buf);

In that case, the plain name (stat) is the name of the non-struct, and the struct must be referred to with the prefix struct. Similarly, the keywords class, union (§8.3), and enum (§8.4) can be used as prefixes for disambiguation. However, it is best not to overload names to make such explicit disambiguation necessary.

In my opinion in the above quote Stroustrup seems to advice against the usage of ‘struct’, ‘class’, ‘union’ and ‘enum’ as mere prefixes.
Registered users can post here. Sign in or register to post.