Hacker News new | ask | show | jobs
by jcelerier 1318 days ago
> Technically, this isn't the case in C either: the type defaults to `int`, but the compiler will pick a larger type if necessary, e.g. `enum Z { a = ((long long)INT_MAX) + 1 };`

if you read this and alarm bells didn't ring in your head I really invite you to immediately go check any enum you may have defined in your code because this is absolutely false with MSVC in C++ (https://gcc.godbolt.org/z/6bqW9rE81) (and C is often compiled as C++ on windows)

1 comments

In practice I don't think that the latitude of making enum size depend on the enumeration has ever been used as it would be too easy to break the ABI. IIRC compilers have allowed forward declaring enums as an extension before c++11 which obviously doesn't work if the size depends on the definition.
I don't think that's true. Neither C nor C++ would allow you to invoke a function with an incomplete type, regardless of whether it is a `struct` or an `enum`, so there's no ABI issues with forward declaring them, but you wouldn't be able to define or invoke a function that takes an incomplete type argument by value.

    struct A;
    enum B; // as you pointed out, not allowed by the C++ standard

    // fine to declare, define, and invoke
    void fooA(struct A*);
    void fooB(enum B*);

    // ok to forward declare, but you can't call them
    void barA(struct A);
    void barB(enum B);
Well I misremembered it seems. You can use forward declared enum class or enum : <type> in C++ as per standard:

   enum class A; // defaults to int
   enum B :int;
   enum C;
   fooA(A);
   FooB(B);
   FooC(C);

   fooA((A)0);
   fooB((B)0);
   fooC((C)0); // error
but indeed GCC refuses plain enum. Forward declaring enums in C is an old GCC extension that still deosn't allow to pass them when incomplete;

Enums in GCC do always default to int or unsigned int, unless -fshot-enums is used which is ABI breaking.

Probably I was misremembering this combination of the int ABI and the forward declaring extension.