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>
usingnamespace 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;
}
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.
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.