Abdul Mateen Abdul Mateen - 11 months ago 76
C++ Question

Why struct node* is written inside a struct node?

I've seen many a times node classes in C++ being defined as:

struct node
whatever data;
struct node* pointerToAnyLinkedNode;

Now the question is why in line no. 4, 'struct' is written before node*? Does it have a special purpose? Because it does not pose any problem if I do not write it. I'm sorry if this question has a duplicate. I could not find one BTW.

Answer Source

It's because this idiom originated in C (where struct types have to be named with struct at the start) and a disturbingly large proportion of the C++ community copy/pastes their code from online tutorials, rather than actually thinking about what they're doing.

(This is also why you'll see struct tm everywhere in C++ code, for no good reason.)

In C++, the struct keyword is redundant here.

To be fair, if you're writing a header and aiming for compatibility with C programs, that's a good reason to leave it in.