Search code examples
c++cstructtypedef

Does declaring struct Name make Name equivalent to struct Name?


I am a bit confused when using struct in c/c++. Traditionally, when I use struct, I usually use it as:

typedef struct Name{
    int a;
};

Name var;

Although it is considered a bad practice from Linus, it's somehow common.

Yet, I wonder

struct Name{
    int a;
};
Name var;

Seems to serve the same purpose, is typedef really necessary? In fact, shouldn't it be

struct Name{
    int a;
};
struct Name var;

Why is the struct from "Name" omitted? If it can always be omitted, does that mean typedef struct is totally useless?


Solution

  • For:

    typedef struct Name{
        int a;
    };
    
    Name var;
    

    The definition should be:

    typedef struct Name{
        int a;
    } Name;
    
    Name var;
    

    Otherwise you are not aliasing the type.


    In C++ this doesn't make sense, when you declare struct Name you can already instantiate Name omitting the struct keyword, as you do in the second code snippet, which would not work for C. It behaves similarly to class, in this regard, you don't declare class Name var;, just Name var;.

    In C I don't agree it's a bad practice, it's a user defined type, why would you always use struct if you can omit it, any programmer worthy of that name should be able to identify a user defined type, it's not rocket science. This though is opinion based. If it's bad practice we will need to revise the whole notion, not only in C++ but also C#, where class and struct keywords are always omitted when instantiating objects.

    As for aliasing pointers, I completely agree, I do not like it one bit, though this can also be seen as opinion based.

    So to answer your direct questions:

    Seems to serve the same purpose, is typedef really necessary?

    For the purpose you describe in C yes, in C++ no.

    Why is the struct from "Name" omitted?

    In C it cannot be ommited, unless you typedefine it, in C++ not only it can, but it should, it's not needed at all.

    If it can always be omitted, does that mean typedef struct is totally useless?

    As you can see, it's not useless.