-2
struct Phant {
   int y;
   struct Phant y;
};

In this code I am getting a compilation error.

On writing the same thing in Java with just a minor change, i.e, replacing struct with class, the code runs perfectly

class Ded {
    int y;
    Ded s = new Ded();
}

Why do I get a compilation error in the first snippet while the second snippet works?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • 1
    You're comparing two totally different languages there and that makes no sense. And `class != struct` – Spikatrix Jun 29 '19 at 06:05
  • Those are not equivalent even from a naming point of view. IFF, they're to be compared, you'd need `Ded` var to be `y`. But, there's no structs in java and a class isn't a struct so... – ChiefTwoPencils Jun 29 '19 at 06:08
  • The Java's code is somewhat equivalent, in C++ terms, to `Phant* y = new Phant()`. This will compile, because now struct consists only of `int y` and `Phant* y`, and therefore its size is known in advance. –  Jun 29 '19 at 06:08
  • 3
    Your structure doesn't compile because `struct Phant y` allocates an `int` and a `struct Phant` which allocates an `int` and a `struct Phant` which allocates an `int` and a `struct Phant` which allocates a ....... See where this is going? – Spikatrix Jun 29 '19 at 06:08
  • First you can not name two data member the same, so change one `y`, second in c++ you can not define struct or class inside itself unless it is a pointer otherwise it will go into a never end loop of definition. – muaz Jun 29 '19 at 06:27

1 Answers1

0

A struct can't contain itself, no matter the language. It would be infinitely large.

However, it's possible that it could contain a pointer/reference to itself like in your Java example (since pointers have a fixed, known size). In C, this is written as follows:

struct Phant {
   int i;
   struct Phant *p;
};

struct Phant p1;
p1.p = malloc(sizeof(struct Phant));
ikegami
  • 367,544
  • 15
  • 269
  • 518