Reputation: 12817
I tried to create a struct that holds a pointer to it's type:
#include <stdio.h>
struct test{
test* t;
};
int main(){
return 0;
}
while compiled with gcc, this code produced an error:
:5:2: error: unknown type name 'test'
but while compiled on g++ it went just fine.
So what I want to understand is:
1) What causes this difference? I thought that if gcc uses one-pass compilation and g++ uses multipass that could explain it, but as I understood, this is not true.
2) How can I avoid this error and define a struct with a pointer to it's own type? (I don't want to use a void* or use casting unless there is no other option)
Upvotes: 1
Views: 2123
Reputation: 610
You need to typedef
struct test
test
;
before you can use it in that way.
This should work just fine:
#include <stdio.h>
struct test{
struct test* t;
};
int main(){
return 0;
}
Or you can try:
#include <stdio.h>
typedef struct test test;
struct test{
test* t;
};
int main(){
return 0;
}
Your problem is gcc is a C compiler and takes types literally. If you use a c++ compiler, it may not care. c++ simplifies the types for you C does not. Be careful of this fact. C code will compile in a c++ compiler but c++ will not compile in a c compiler.
Upvotes: 0
Reputation: 7352
Your syntax is incorrect in "C". You have to use struct <structname>* <varname>;
in format.
In c++, you can omit the "struct" in front of it. In C however, you have to write it to define a pointer to your struct.
Fixed code:
#include <stdio.h>
typedef struct test{
struct test* t;
} test;
int main(){
return 0;
}
Upvotes: 2
Reputation: 1903
You have to write struct before test* t to define a pointer to our struct:
struct test* t;
That is one different between C and C++.
Upvotes: 6