1

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)

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

3 Answers3

6

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++.

Viatorus
  • 1,804
  • 1
  • 18
  • 41
2

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

Live demo

Magisch
  • 7,312
  • 9
  • 36
  • 52
0

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.

haelmic
  • 541
  • 4
  • 18
  • 1
    "*C code will compile in a c++ compiler*" - most C code isn't valid C++. – melpomene Jul 18 '16 at 06:31
  • It depends if you are using strict mode or not. Depending on the c++ compiler to ensure backwards compatibility the compiler will just do it. – haelmic Jul 18 '16 at 06:35