Reputation: 429
I am currently learning pointers and structs, and I cant understand the following
typedef struct at atom;
struct at {
int element = 5;
struct at *next;
}
how come this code doesn't throw an error?
and when I create an atom using
atom x;
printf("%d", x.element);
it will print 5.
I don't understand the typedefing of non-existing structure, how does that work?
Upvotes: 1
Views: 336
Reputation: 5637
typedef struct at atom;
Here, you are declaring a struct
called at
and giving it a typedef
of atom
. So that is completely valid C.
struct at {
int element = 5;
struct at *next;
}
Here, you are defining the struct at
that you declared earlier.
NOTE:
It is important to note that in C, you are not allowed to initialize variables within a struct like you do here:
struct at {
int element = 5; // <---- Illegal in C
struct at *next;
}
However, this is perfectly okay in C++ so if you're trying to use C, remove the variable initialization, but if you're working with C++ then it's fine the way it is.
Upvotes: 4
Reputation: 311126
You forgot to place a semicolon
typedef struct at atom;
struct at {
int element = 5;
struct at *next;
}
^^^^
Take into account that it is a C++ code. In C you may not initialize data members of a structure within its definition.
This declaration
typedef struct at atom;
declares two things. First of all it declares new type struct at
in the current declarative region. And it declares an alias for this type atom
It is not necessary that each declaration would be at the same time a definition.
At first struct at
is declared and then it is defined
struct at {
int element = 5;
struct at *next;
};
Compare thsi approach for example with functions. Functions also may be several times declared and only one time defined. For example
void f();
void f();
//...
void f();
void f() { std::cout << "It is a joke" << std::endl; }
The same way a structure may be several times declared but only one time defined.
Upvotes: 1
Reputation: 100652
It's a forward declaration — in C you are permitted to declare that a named thing will exist without giving details about it until later; that's most common used to allow cycles of knowledge; e.g. struct A
has a pointer to struct B
, struct B
has a pointer to struct C
, and struct C
has a pointer to struct A
. In that specific case, as long as you've said that the things are structs then the compiler knows enough about the type to know what an appropriate pointer will look like.
In this case you've declared that there will be a struct called at
and that you'll want to refer to it as atom
. If you were to try to declare an atom
before telling the compiler what struct at
looks like, that'd be an error. But until then the compiler has enough information to proceed.
Upvotes: 2