Reputation: 2410
My lecturer just astounded me by insisting that the following is a valid C++ statement:
struct charlistrecord *next
The complete condition was found in declaring a recursive datatype in C/C++ as follows:
typedef struct charlistrecord
{
char data;
struct charlistrecord *next;
} *charlist;
I want to know whether maybe there has been a time when this was accepted syntax or whether I've just been dumb for months of thinking I know C++.
Upvotes: 2
Views: 147
Reputation: 66194
Prior to C++ and the assumption of typedefs, the only way to get a typed structure was via this syntax, and it was the only way to get a self-type-linked node.
struct Foo
{
int val;
struct Foo *link;
};
In C, this required any usage of Foo to be:
struct Foo foo;
struct Foo *foo_ptr;
etc..
A typedef helped for this by doing this:
typedef struct Foo
{
int val;
struct Foo *link;
} Foo;
Since now you could do this:
Foo foo; // same as struct Foo
Foo *foo_ptr; // same as struct Foo *
Note: Using a typedef to alias a struct Name
is not restricted to Name
as the alias. Yo were perfectly valid to do this as well:
typedef struct Foo
{
int val;
struct Foo *link;
} Bar;
and now the following are doable;
struct Foo foo;
Bar bar;
struct Foo *fooptr = &bar;
Bar *barptr = &foo;
Really makes you wish you programmed in C back in the day, doesn't it ? Probably doesn't clear things up, but hopefully a little less gray.
Upvotes: 2
Reputation: 171127
It's perfectly valid, and it can even be useful if your struct's name is shadowed by a variable, like here:
struct C {};
int C = 0;
int a;
void foo() {
C *a; // multiplies int C by int a
struct C *a; //defines 'a' as pointer to struct C
}
Upvotes: 0
Reputation: 29966
Yes it's totally valid. The word struct
here just explicitly states that next
is a pointer to a structure type named charlistrecord
.
It's a reminiscence from C, and you might as well omit the keyword in C++, but if you want to use it, you can.
Upvotes: 1
Reputation: 8027
It's a hangover from C. In C this is how you have to declare struct variables and members, so it's legal in C++ for reasons of backwards compatibility. Sounds like your lecturer is a bit 'old school'.
Upvotes: 1