Hacker News new | ask | show | jobs
by WickedSmoke 1137 days ago
The most desired C++ feature I'd like to see is the automatic typedef'ing of structures. Does anyone know why such a fundamental thing hasn't been implemented yet?
3 comments

I disagree that this is a fundamental thing.

C++ doesn't exactly do "automatic typedef'ing of structures".

The difference is that in C++, if you define a type "struct foo", you can refer to it either as "struct foo" or as "foo" (likewise for class, union, and enum).

In C, if you define a type "struct foo", its name is "struct foo". If you want to call it "foo", you have to define an alias using "typedef".

Personally, I see "struct foo" as a perfectly valid name. I seldom feel the need to define another name for it. (typedef is the only way that a C type's name can be a single user-defined identifier; "int", "char" et al are keywords.)

I'll define a typedef for a struct type only if the code that uses it shouldn't know that it's a struct type.

Yes, it's a little extra typing. I save up the keystrokes I save by typing "{" rather than "BEGIN" and use them to type "struct". 8-)}

This is a matter of personal taste, and if you want to call it "foo", there are common idioms for doing that.

The common workaround isn't too bad:

    typedef struct { float x, y; } vec2;
...or if forward declaration is needed via a named struct:

    typedef struct vec2 { float x, y; } vec2;
Because it would break a lot of existing code.
How would using an existing structure definition where an undefined type is found break anything?

Compilers already know what you want to do as it will print an error such as: "unknown type name ‘Vec’; use ‘struct’ keyword to refer to the type".

So you want Vec to refer to struct Vec but only if there is no other type Vec defined before or until one is defined later? That would work, but might be a bit confusing.
C++ has struct & typedef and things work quite naturally. It always seemed like an obvious thing to bring to C, but I'm not sure about the nuances of the rules governing this.
C++ had this forever (I assume), but for C this would be a breaking change which we try very hard to avoid.
Could you please give an example of what would break? Perhaps I'm being dense, but it seems a new C standard supporting this would still compile existing code just as C++ can.
That's how it works for an object's attributes inside methods, since this is optional by default. I hate it but there's precedent.