cstructlanguage-lawyerc23

Has C always required "struct" in front of a struct name, if the typedef with the same name was not declared?


In Modern C by Jens Gustedt, I read that

For historical reasons (again!), the name that we introduce for the structure always has to be preceded by the keyword struct, which makes its use a bit clumsy. Also, many C beginners run into difficulties with this when they forget the struct keyword and the compiler throws an incomprehensible error at them.

There is a general tool that can help us avoid that by giving a symbolic name to an otherwise existing type: typedef. Using it, a type can have several names, and we can even reuse the tag nameC that we used in the structure declaration:

typedef struct birdStruct birdStructure;
typedef struct birdStruct birdStruct;

Then, struct birdStruct, birdStruct, and birdStructure can all be used interchangeably.

which seems to be in line, for instance, with this answer, which from 2014.

But then, in this tutorial on OOP in C, the examples seem to lack that struct, even if they don't use the typedef "trick".

Since the post is from 6 years ago, I was wondering if the C standard allowed that type of code, or maybe the author of the post is assuming some compilation flags or something else. Or is it just a typo?


Solution

  • But then, in this tutorial on OOP in C, the examples seem to lack that struct, even if they don't use the typedef "trick".

    Here is a sample from that web page of what is apparently intended to be C code:

    struct Shape;
    struct ShapeType; 
    
    ShapeType* ShapeType__create(
    …
    

    Since the post is from 6 years ago, I was wondering if the C standard allowed that type of code, or maybe the author of the post is assuming some compilation flags or something else. Or is it just a typo?

    No version of the C standard has provided that struct ShapeType would provide a type that could be used as ShapeType* ShapeType__create….

    C 1990 6.1.2.3 says:

    Thus, there are name spaces for various categories of identifiers, as follows:

    – the tags of structures, unions, and enumerations (disambiguated by following any of the keywords struct, union, or enum).

    Later versions of the standard similarly separate the name spaces, and nothing in them says declaring a tag makes the tag’s name available as a type name.