Search code examples
c++c++17typedef

What is the correct placement of names and types in the typedef syntax?


Usually the syntax of typedef is as follows

typedef <existing_name> <new_name>

But in the following case, I am bit confused

  typedef char yes[1];
  typedef char no[2];

This above seems to work. Why and how?

Shouldn't this be written as below?

  typedef yes char[1];
  typedef no char[2];

Solution

  • Usually the syntax of typedef is...

    No, that's not accurate. The usual syntax is

    typedef <variable declaration>;
    

    Then the declaration is decomposed, and the name of the variable becomes a new name for the type the variable would have had. The case you are confused about is inline with that. In the absence of typedef, that's how you'd declare an array variable. Add a typedef, and the variable name becomes a new name for the type.

    Of course, a modern type alias will actually look more like what you expect

    using yes = char[1];
    using no  = char[2];
    

    Which is good in the sense that it doesn't require one to understnad C++'s declarator syntax just to see what the name of the type is. One still has to understand the syntax to write the type on the right hand side, though...